GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix the TextMate scheduler clock and let newer revisions cancel the r… · opencode-mobile/opencode-mobile@12e8e28

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • android/app/src
    • main/java/dev/opencode/mobile/domain/textmate
      • AndroidTextMateHighlightingEngine.kt
    • test/java/dev/opencode/mobile/domain/textmate
      • AndroidTextMateHighlightingEngineTest.kt
  • ios/OpenCode Mobile
    • OpenCode MobileTests/Domain/TextMate
      • TextMateHighlightingEngineTests.swift
    • OpenCode Mobile/Domain/TextMate
      • TextMateHighlightingEngine.swift
  • shared/markdown-core/src
    • androidMain/kotlin/dev/opencode/mobile/markdown
      • TextMateSchedulerLock.android.kt
    • androidUnitTest/kotlin/dev/opencode/mobile/markdown
      • OpenCodeTextMateSchedulerBridgeConcurrencyTest.kt
    • commonMain/kotlin/dev/opencode/mobile/markdown
      • OpenCodeTextMateSchedulerBridge.kt
      • TextMateRequestScheduler.kt
      • TextMateSchedulerLock.kt
    • commonTest/kotlin/dev/opencode/mobile/markdown
      • TextMateRequestSchedulerTest.kt
    • iosMain/kotlin/dev/opencode/mobile/markdown
      • TextMateSchedulerLock.ios.kt
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/domain/textmate/AndroidTextMateHighlightingEngine.kt‎

Copy file name to clipboardExpand all lines: android/app/src/main/java/dev/opencode/mobile/domain/textmate/AndroidTextMateHighlightingEngine.kt
+78-76Lines changed: 78 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,33 @@ import dev.opencode.mobile.markdown.emptyResult
1414
import kotlinx.coroutines.CompletableDeferred
1515
import kotlinx.coroutines.CoroutineDispatcher
1616
import kotlinx.coroutines.CoroutineScope
17-
import kotlinx.coroutines.Job
1817
import kotlinx.coroutines.SupervisorJob
1918
import kotlinx.coroutines.launch
2019
import kotlinx.coroutines.sync.Mutex
2120
import kotlinx.coroutines.sync.withLock
2221
import kotlinx.coroutines.withContext
22+
import kotlinx.coroutines.yield
2323
import kotlin.coroutines.cancellation.CancellationException
2424

2525
/**
2626
* Android's asynchronous platform-to-KMP adapter. The dispatcher keeps TextMate
2727
* off the UI executor. The shared [TextMateRequestScheduler] owns queue policy;
2828
* this adapter drives at most one active highlight job.
29+
*
30+
* Only highlight jobs and cache trims run on [ownerDispatcher]. Admits take [owner]
31+
* on the caller's thread, so a newer revision can cancel the job that is running.
2932
*/
3033
class AndroidTextMateHighlightingEngine(
3134
private val delegateFactory: () -> TextMateHighlightingEngine,
3235
private val ownerDispatcher: CoroutineDispatcher,
3336
private val scheduler: TextMateRequestScheduler = TextMateRequestScheduler(),
3437
) : TextMateHighlightingEngine {
38+
// Guards scheduler, waiters, and pumping; never held while a job runs.
3539
private val owner = Mutex()
3640
private val scope = CoroutineScope(SupervisorJob() + ownerDispatcher)
3741
private val waiters = mutableMapOf<Long, CompletableDeferred<HighlightResult>>()
3842
private var delegate: TextMateHighlightingEngine? = null
39-
private var pumpJob: Job? = null
43+
private var pumping = false
4044

4145
constructor(
4246
delegate: TextMateHighlightingEngine,
@@ -50,102 +54,100 @@ class AndroidTextMateHighlightingEngine(
5054

5155
override suspend fun highlight(request: HighlightRequest): HighlightResult {
5256
val deferred =
53-
withContext(ownerDispatcher) {
54-
owner.withLock {
55-
val admit = scheduler.admit(request)
56-
for (completion in admit.completed) {
57-
waiters.remove(completion.ticketId)?.complete(completion.result)
58-
}
59-
val ticketId = admit.ticketId
60-
if (ticketId == null) {
61-
val rejected =
62-
admit.completed
63-
.lastOrNull {
64-
it.request.key == request.key && it.request.revision == request.revision
65-
}?.result
66-
?: admit.completed.last().result
67-
return@withLock CompletableDeferred(rejected)
68-
}
69-
val waiter = CompletableDeferred<HighlightResult>()
70-
waiters[ticketId] = waiter
71-
ensurePumpLocked()
72-
waiter
57+
owner.withLock {
58+
val admit = scheduler.admit(request)
59+
for (completion in admit.completed) {
60+
waiters.remove(completion.ticketId)?.complete(completion.result)
7361
}
62+
val ticketId = admit.ticketId
63+
if (ticketId == null) {
64+
val rejected =
65+
admit.completed
66+
.lastOrNull {
67+
it.request.key == request.key && it.request.revision == request.revision
68+
}?.result
69+
?: admit.completed.last().result
70+
return@withLock CompletableDeferred(rejected)
71+
}
72+
val waiter = CompletableDeferred<HighlightResult>()
73+
waiters[ticketId] = waiter
74+
ensurePumpLocked()
75+
waiter
7476
}
7577
return deferred.await()
7678
}
7779

7880
override suspend fun trim(level: MemoryPressure) {
79-
withContext(ownerDispatcher) {
80-
owner.withLock {
81-
for (completion in scheduler.trim(level)) {
82-
waiters.remove(completion.ticketId)?.complete(completion.result)
83-
}
84-
ownedDelegate().trim(level)
81+
owner.withLock {
82+
for (completion in scheduler.trim(level)) {
83+
waiters.remove(completion.ticketId)?.complete(completion.result)
8584
}
8685
}
86+
withContext(ownerDispatcher) {
87+
ownedDelegate().trim(level)
88+
}
8789
}
8890

8991
suspend fun setLowPowerOrThermal(disabled: Boolean) {
90-
withContext(ownerDispatcher) {
91-
owner.withLock {
92-
scheduler.setLowPowerOrThermal(disabled)
93-
}
92+
owner.withLock {
93+
scheduler.setLowPowerOrThermal(disabled)
9494
}
9595
}
9696

9797
override fun schedulerSnapshot(): TextMateSchedulerSnapshot = scheduler.snapshot()
9898

9999
private fun ensurePumpLocked() {
100-
if (pumpJob?.isActive == true) return
101-
pumpJob =
102-
scope.launch {
103-
while (true) {
104-
val job =
105-
owner.withLock {
106-
scheduler.pickNext()
107-
} ?: break
108-
val raw =
109-
try {
110-
when (val active = ownedDelegate()) {
111-
is OpenCodeTextMateHighlightingEngine ->
112-
active.highlightNow(job.request, shouldCancel = job.cancelRequested)
113-
else -> active.highlight(job.request)
114-
}
115-
} catch (cancelled: CancellationException) {
116-
throw cancelled
117-
} catch (error: Throwable) {
118-
emptyResult(
119-
request = job.request,
120-
outcome = TextMateParseOutcome.Failed,
121-
queueWaitNanoseconds = job.queueWaitNanoseconds,
122-
schedulingReason = null,
123-
).copy(
124-
diagnostics =
125-
listOf(
126-
MarkdownDiagnostic(
127-
kind = MarkdownDiagnosticKind.HighlighterFallback,
128-
message = error.message ?: "TextMate highlighting failed.",
129-
),
130-
),
131-
observation =
132-
emptyResult(
133-
request = job.request,
134-
outcome = TextMateParseOutcome.Failed,
135-
queueWaitNanoseconds = job.queueWaitNanoseconds,
136-
schedulingReason = null,
137-
).observation.copy(
138-
diagnosticKinds = listOf(MarkdownDiagnosticKind.HighlighterFallback),
139-
),
140-
)
141-
}
100+
if (pumping) return
101+
pumping = true
102+
scope.launch {
103+
while (true) {
104+
val job =
142105
owner.withLock {
143-
for (completion in scheduler.finishActive(job.ticketId, raw)) {
144-
waiters.remove(completion.ticketId)?.complete(completion.result)
106+
scheduler.pickNext().also { next -> if (next == null) pumping = false }
107+
} ?: break
108+
val raw =
109+
try {
110+
when (val active = ownedDelegate()) {
111+
is OpenCodeTextMateHighlightingEngine ->
112+
active.highlightNow(job.request, shouldCancel = job.cancelRequested)
113+
else -> active.highlight(job.request)
145114
}
115+
} catch (cancelled: CancellationException) {
116+
throw cancelled
117+
} catch (error: Throwable) {
118+
emptyResult(
119+
request = job.request,
120+
outcome = TextMateParseOutcome.Failed,
121+
queueWaitNanoseconds = job.queueWaitNanoseconds,
122+
schedulingReason = null,
123+
).copy(
124+
diagnostics =
125+
listOf(
126+
MarkdownDiagnostic(
127+
kind = MarkdownDiagnosticKind.HighlighterFallback,
128+
message = error.message ?: "TextMate highlighting failed.",
129+
),
130+
),
131+
observation =
132+
emptyResult(
133+
request = job.request,
134+
outcome = TextMateParseOutcome.Failed,
135+
queueWaitNanoseconds = job.queueWaitNanoseconds,
136+
schedulingReason = null,
137+
).observation.copy(
138+
diagnosticKinds = listOf(MarkdownDiagnosticKind.HighlighterFallback),
139+
),
140+
)
141+
}
142+
owner.withLock {
143+
for (completion in scheduler.finishActive(job.ticketId, raw)) {
144+
waiters.remove(completion.ticketId)?.complete(completion.result)
146145
}
147146
}
147+
// Let a queued cache trim run on the owner dispatcher between jobs.
148+
yield()
148149
}
150+
}
149151
}
150152

151153
private fun ownedDelegate(): TextMateHighlightingEngine = delegate ?: delegateFactory().also { created -> delegate = created }
Collapse file

‎android/app/src/test/java/dev/opencode/mobile/domain/textmate/AndroidTextMateHighlightingEngineTest.kt‎

Copy file name to clipboardExpand all lines: android/app/src/test/java/dev/opencode/mobile/domain/textmate/AndroidTextMateHighlightingEngineTest.kt
+87Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,18 @@ import dev.opencode.mobile.markdown.HighlightRequest
66
import dev.opencode.mobile.markdown.HighlightResult
77
import dev.opencode.mobile.markdown.HighlightRevision
88
import dev.opencode.mobile.markdown.MarkdownDiagnosticKind
9+
import dev.opencode.mobile.markdown.OpenCodeCodeHighlighter
10+
import dev.opencode.mobile.markdown.OpenCodeTextMateHighlightingEngine
11+
import dev.opencode.mobile.markdown.OpenCodeTextMateMetricsSink
12+
import dev.opencode.mobile.markdown.SyntaxHighlightResult
13+
import dev.opencode.mobile.markdown.SyntaxHighlightSource
914
import dev.opencode.mobile.markdown.TextMateHighlightingEngine
1015
import dev.opencode.mobile.markdown.TextMateParseObservation
1116
import dev.opencode.mobile.markdown.TextMateParseOutcome
1217
import dev.opencode.mobile.markdown.TextMateRequestScheduler
1318
import dev.opencode.mobile.markdown.TextMateSchedulerLimits
1419
import kotlinx.coroutines.CompletableDeferred
20+
import kotlinx.coroutines.Dispatchers
1521
import kotlinx.coroutines.asCoroutineDispatcher
1622
import kotlinx.coroutines.async
1723
import kotlinx.coroutines.awaitAll
@@ -22,7 +28,10 @@ import org.junit.Assert.assertEquals
2228
import org.junit.Assert.assertTrue
2329
import org.junit.Test
2430
import java.util.concurrent.ConcurrentLinkedQueue
31+
import java.util.concurrent.CountDownLatch
2532
import java.util.concurrent.Executors
33+
import java.util.concurrent.TimeUnit
34+
import java.util.concurrent.atomic.AtomicBoolean
2635
import java.util.concurrent.atomic.AtomicInteger
2736

2837
class AndroidTextMateHighlightingEngineTest {
@@ -137,6 +146,43 @@ class AndroidTextMateHighlightingEngineTest {
137146
}
138147
}
139148

149+
@Test
150+
fun newerRevisionCancelsJobThatBlocksTheOwnerThread() =
151+
runBlocking {
152+
val highlighter = BlockingUntilCancelledHighlighter()
153+
val executor =
154+
Executors.newSingleThreadExecutor { runnable ->
155+
Thread(runnable, "textmate-owner-test")
156+
}
157+
val dispatcher = executor.asCoroutineDispatcher()
158+
try {
159+
val engine =
160+
AndroidTextMateHighlightingEngine(
161+
OpenCodeTextMateHighlightingEngine(highlighter),
162+
dispatcher,
163+
)
164+
val first =
165+
async(Dispatchers.Default) {
166+
engine.highlight(request(key = "block", revision = 1))
167+
}
168+
assertTrue(highlighter.entered.await(2, TimeUnit.SECONDS))
169+
val second =
170+
async(Dispatchers.Default) {
171+
engine.highlight(request(key = "block", revision = 2))
172+
}
173+
174+
withTimeout(1_000) {
175+
assertEquals(TextMateParseOutcome.Cancelled, first.await().outcome)
176+
assertEquals(TextMateParseOutcome.Highlighted, second.await().outcome)
177+
}
178+
assertTrue(highlighter.sawCancel.get())
179+
} finally {
180+
highlighter.giveUp.countDown()
181+
// Graceful: a dropped queued admit would leave runBlocking waiting forever.
182+
executor.shutdown()
183+
}
184+
}
185+
140186
@Test
141187
fun initializerErrorDuringHighlightDoesNotEscapePump() =
142188
runBlocking {
@@ -177,6 +223,47 @@ class AndroidTextMateHighlightingEngineTest {
177223
policyEpoch = 1,
178224
)
179225

226+
/** Spins on its thread, like a real tokenizer, until the job is cancelled. Later calls return at once. */
227+
private class BlockingUntilCancelledHighlighter : OpenCodeCodeHighlighter {
228+
val entered = CountDownLatch(1)
229+
val giveUp = CountDownLatch(1)
230+
val sawCancel = AtomicBoolean(false)
231+
private val calls = AtomicInteger(0)
232+
233+
override fun supportsLanguage(languageOrAlias: String?): Boolean = true
234+
235+
override fun highlight(
236+
languageOrAlias: String?,
237+
code: String,
238+
): SyntaxHighlightResult = result()
239+
240+
override fun highlight(
241+
languageOrAlias: String?,
242+
code: String,
243+
metricsSink: OpenCodeTextMateMetricsSink,
244+
shouldCancel: () -> Boolean,
245+
): SyntaxHighlightResult {
246+
if (calls.incrementAndGet() > 1) return result()
247+
entered.countDown()
248+
while (giveUp.count > 0) {
249+
if (shouldCancel()) {
250+
sawCancel.set(true)
251+
return result(TextMateParseOutcome.Cancelled)
252+
}
253+
Thread.onSpinWait()
254+
}
255+
return result()
256+
}
257+
258+
private fun result(outcome: TextMateParseOutcome? = null) =
259+
SyntaxHighlightResult(
260+
spans = emptyList(),
261+
diagnostics = emptyList(),
262+
source = SyntaxHighlightSource.TextMate,
263+
textMateOutcome = outcome,
264+
)
265+
}
266+
180267
private class RacingEngine : TextMateHighlightingEngine {
181268
val maximumActive = AtomicInteger(0)
182269
val completed = AtomicInteger(0)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.