Scoop API

scoop:scoop.http.client:0.1.0

src/cache/close.scoop

Selected production source · src/cache/close.scoop

1package scoop.http.client
3import scoop.asyncio.currentEventLoop
4import scoop.platform.fs.Path
5import scoop.platform.system.PlatformErrorKind
6import scoop.platform.system.PlatformException
8internal class ClientCacheClosure {
9 private val lock: ClientLock = ClientLock()
10 private var started: Boolean = false
11 private var done: Boolean = false
12 private var failure: Throwable? = None
13 private val waiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()
15 suspend fun close(action: suspend () -> Unit) {
16 val first =
17 lock.withLock {
18 if (started)
19 false
20 else {
21 started = true;
22 true
23 }
24 }
25 if (first) {
26 var failed: Throwable? = None
27 try {
28 nonCancellableScope<Unit> { action() }
29 }
30 catch (error: Throwable) {
31 failed = Some(error)
32 }
33 val result = failed
34 val waiting =
35 lock.withLock {
36 done = true;
37 failure = result
38 val saved = waiters.toArray();
39 waiters.clear();
40 saved
41 }
42 for (waiter in waiting)
43 when (failed) {
44 case Some(val error) -> waiter.resumeWithException(error)
45 case None -> waiter.resume(Unit)
46 }
47 if (clientPresent(failed))
48 throw failed!!
49 } else {
50 suspendCoroutine<Unit> {
51 continuation ->
52 val finished =
53 lock.withLock {
54 if (done)
55 true
56 else {
57 waiters.add(continuation);
58 false
59 }
60 }
61 if (finished)
62 when (lock.withLock { failure }) {
63 case Some(val error) -> continuation.resumeWithException(error)
64 case None -> continuation.resume(Unit)
65 }
66 }
67 }
68 }
71internal suspend fun deleteClientCacheFile(path: Path) {
72 try {
73 currentEventLoop().deleteFile(path)
74 }
75 catch (error: PlatformException) {
76 if (error.kind != PlatformErrorKind.NotFound)
77 throw error
78 }
81internal suspend fun deleteClientCacheFiles(paths: List<Path>) {
82 if (paths.size == 0L)
83 return
84 nonCancellableScope<Unit> {
85 var failure: Throwable? = None
86 for (path in paths) {
87 try {
88 deleteClientCacheFile(path)
89 }
90 catch (error: Throwable) {
91 failure = Some(clientCombined(failure, error))
92 }
93 }
94 if (clientPresent(failure))
95 throw failure!!
96 }