@kesha-antonov/react-native-background-downloader 4.5.8 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +30 -3
  2. package/android/build.gradle +17 -0
  3. package/android/src/main/AndroidManifest.xml +24 -0
  4. package/android/src/main/java/com/eko/DownloadConstants.kt +14 -2
  5. package/android/src/main/java/com/eko/Downloader.kt +77 -12
  6. package/android/src/main/java/com/eko/PromiseExtensions.kt +36 -0
  7. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +82 -134
  8. package/android/src/main/java/com/eko/ResumableDownloadService.kt +0 -4
  9. package/android/src/main/java/com/eko/ResumableDownloader.kt +121 -12
  10. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +65 -9
  11. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +64 -0
  12. package/android/src/main/java/com/eko/uidt/RNBGDFileProvider.kt +17 -0
  13. package/android/src/main/java/com/eko/uidt/UIDTJobIds.kt +112 -0
  14. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +178 -17
  15. package/android/src/main/java/com/eko/uidt/UIDTJobState.kt +23 -1
  16. package/android/src/main/java/com/eko/uidt/UIDTNotificationIds.kt +73 -0
  17. package/android/src/main/java/com/eko/uidt/UIDTNotificationManager.kt +246 -19
  18. package/android/src/main/java/com/eko/utils/ReadableConverters.kt +55 -0
  19. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +97 -0
  20. package/android/src/main/java/com/eko/utils/StorageManager.kt +13 -0
  21. package/android/src/main/res/xml/rnbgd_file_paths.xml +23 -0
  22. package/android/src/newarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  23. package/android/src/oldarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  24. package/android/src/test/java/com/eko/ResumableDownloaderConcurrencyTest.kt +199 -0
  25. package/android/src/test/java/com/eko/uidt/UIDTJobIdsTest.kt +159 -0
  26. package/android/src/test/java/com/eko/uidt/UIDTJobManagerTest.kt +192 -0
  27. package/android/src/test/java/com/eko/uidt/UIDTNotificationIdsTest.kt +99 -0
  28. package/ios/RNBackgroundDownloader.mm +187 -91
  29. package/lib/DownloadTask.js +8 -7
  30. package/lib/NativeRNBackgroundDownloader.d.ts +2 -0
  31. package/lib/UploadTask.js +11 -10
  32. package/lib/config.d.ts +3 -10
  33. package/lib/config.js +4 -44
  34. package/lib/index.d.ts +1 -1
  35. package/lib/index.js +43 -34
  36. package/lib/logger.d.ts +2 -0
  37. package/lib/logger.js +16 -0
  38. package/lib/notifications.d.ts +8 -0
  39. package/lib/notifications.js +35 -0
  40. package/lib/types.d.ts +19 -0
  41. package/package.json +8 -3
  42. package/src/DownloadTask.ts +2 -1
  43. package/src/NativeRNBackgroundDownloader.ts +8 -1
  44. package/src/UploadTask.ts +2 -1
  45. package/src/config.ts +9 -45
  46. package/src/index.ts +22 -2
  47. package/src/logger.ts +16 -0
  48. package/src/notifications.ts +32 -0
  49. package/src/types.ts +19 -0
@@ -33,34 +33,16 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
33
33
  }
34
34
 
35
35
  @ReactMethod
36
- fun pauseTask(id: String, promise: Promise) {
37
- try {
38
- impl.pauseTask(id)
39
- promise.resolve(null)
40
- } catch (e: Exception) {
41
- promise.reject("ERR_PAUSE_TASK", e.message, e)
42
- }
43
- }
36
+ fun pauseTask(id: String, promise: Promise) =
37
+ promise.resolveCatching("ERR_PAUSE_TASK") { impl.pauseTask(id) }
44
38
 
45
39
  @ReactMethod
46
- fun resumeTask(id: String, promise: Promise) {
47
- try {
48
- impl.resumeTask(id)
49
- promise.resolve(null)
50
- } catch (e: Exception) {
51
- promise.reject("ERR_RESUME_TASK", e.message, e)
52
- }
53
- }
40
+ fun resumeTask(id: String, promise: Promise) =
41
+ promise.resolveCatching("ERR_RESUME_TASK") { impl.resumeTask(id) }
54
42
 
55
43
  @ReactMethod
56
- fun stopTask(id: String, promise: Promise) {
57
- try {
58
- impl.stopTask(id)
59
- promise.resolve(null)
60
- } catch (e: Exception) {
61
- promise.reject("ERR_STOP_TASK", e.message, e)
62
- }
63
- }
44
+ fun stopTask(id: String, promise: Promise) =
45
+ promise.resolveCatching("ERR_STOP_TASK") { impl.stopTask(id) }
64
46
 
65
47
  @ReactMethod
66
48
  fun updateTaskHeaders(id: String, headers: ReadableMap, promise: Promise) {
@@ -68,23 +50,12 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
68
50
  }
69
51
 
70
52
  @ReactMethod
71
- fun completeHandler(jobId: String, promise: Promise) {
72
- try {
73
- impl.completeHandler(jobId)
74
- promise.resolve(null)
75
- } catch (e: Exception) {
76
- promise.reject("ERR_COMPLETE_HANDLER", e.message, e)
77
- }
78
- }
53
+ fun completeHandler(jobId: String, promise: Promise) =
54
+ promise.resolveCatching("ERR_COMPLETE_HANDLER") { impl.completeHandler(jobId) }
79
55
 
80
56
  @ReactMethod
81
- fun getExistingDownloadTasks(promise: Promise) {
82
- try {
83
- impl.getExistingDownloadTasks(promise)
84
- } catch (e: Exception) {
85
- promise.reject("ERR_GET_EXISTING_TASKS", e.message, e)
86
- }
87
- }
57
+ fun getExistingDownloadTasks(promise: Promise) =
58
+ promise.rejectOnThrow("ERR_GET_EXISTING_TASKS") { impl.getExistingDownloadTasks(promise) }
88
59
 
89
60
  @ReactMethod
90
61
  fun setLogsEnabled(enabled: Boolean) {
@@ -124,41 +95,18 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
124
95
  }
125
96
 
126
97
  @ReactMethod
127
- fun pauseUploadTask(id: String, promise: Promise) {
128
- try {
129
- impl.pauseUploadTask(id)
130
- promise.resolve(null)
131
- } catch (e: Exception) {
132
- promise.reject("ERR_PAUSE_UPLOAD_TASK", e.message, e)
133
- }
134
- }
98
+ fun pauseUploadTask(id: String, promise: Promise) =
99
+ promise.resolveCatching("ERR_PAUSE_UPLOAD_TASK") { impl.pauseUploadTask(id) }
135
100
 
136
101
  @ReactMethod
137
- fun resumeUploadTask(id: String, promise: Promise) {
138
- try {
139
- impl.resumeUploadTask(id)
140
- promise.resolve(null)
141
- } catch (e: Exception) {
142
- promise.reject("ERR_RESUME_UPLOAD_TASK", e.message, e)
143
- }
144
- }
102
+ fun resumeUploadTask(id: String, promise: Promise) =
103
+ promise.resolveCatching("ERR_RESUME_UPLOAD_TASK") { impl.resumeUploadTask(id) }
145
104
 
146
105
  @ReactMethod
147
- fun stopUploadTask(id: String, promise: Promise) {
148
- try {
149
- impl.stopUploadTask(id)
150
- promise.resolve(null)
151
- } catch (e: Exception) {
152
- promise.reject("ERR_STOP_UPLOAD_TASK", e.message, e)
153
- }
154
- }
106
+ fun stopUploadTask(id: String, promise: Promise) =
107
+ promise.resolveCatching("ERR_STOP_UPLOAD_TASK") { impl.stopUploadTask(id) }
155
108
 
156
109
  @ReactMethod
157
- fun getExistingUploadTasks(promise: Promise) {
158
- try {
159
- impl.getExistingUploadTasks(promise)
160
- } catch (e: Exception) {
161
- promise.reject("ERR_GET_EXISTING_UPLOAD_TASKS", e.message, e)
162
- }
163
- }
110
+ fun getExistingUploadTasks(promise: Promise) =
111
+ promise.rejectOnThrow("ERR_GET_EXISTING_UPLOAD_TASKS") { impl.getExistingUploadTasks(promise) }
164
112
  }
@@ -0,0 +1,199 @@
1
+ package com.eko
2
+
3
+ import okhttp3.mockwebserver.Dispatcher
4
+ import okhttp3.mockwebserver.MockResponse
5
+ import okhttp3.mockwebserver.MockWebServer
6
+ import okhttp3.mockwebserver.RecordedRequest
7
+ import org.junit.After
8
+ import org.junit.Assert.assertEquals
9
+ import org.junit.Assert.assertTrue
10
+ import org.junit.Before
11
+ import org.junit.Rule
12
+ import org.junit.Test
13
+ import org.junit.rules.TemporaryFolder
14
+ import org.junit.runner.RunWith
15
+ import org.robolectric.RobolectricTestRunner
16
+ import org.robolectric.annotation.Config
17
+ import java.util.concurrent.ConcurrentHashMap
18
+ import java.util.concurrent.CopyOnWriteArrayList
19
+ import java.util.concurrent.CountDownLatch
20
+ import java.util.concurrent.TimeUnit
21
+
22
+ /**
23
+ * The library's own downloader is the one path with no scheduler in front of it:
24
+ * before `maxParallelDownloads` applied here, every download took a thread and a
25
+ * socket of its own the moment it started. These pin the cap that replaced that.
26
+ */
27
+ @RunWith(RobolectricTestRunner::class)
28
+ @Config(sdk = [34])
29
+ class ResumableDownloaderConcurrencyTest {
30
+
31
+ @get:Rule
32
+ val tempFolder = TemporaryFolder()
33
+
34
+ private lateinit var server: MockWebServer
35
+ private lateinit var downloader: ResumableDownloader
36
+
37
+ /** Held closed while a request is being served, so transfers stay in flight. */
38
+ private val holdResponses = CountDownLatch(1)
39
+ private val requested = CopyOnWriteArrayList<String>()
40
+
41
+ private val completed = CopyOnWriteArrayList<String>()
42
+ private val failed = ConcurrentHashMap<String, String>()
43
+
44
+ private val listener = object : ResumableDownloader.DownloadListener {
45
+ override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
46
+ override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
47
+ override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
48
+ completed.add(id)
49
+ }
50
+ override fun onError(id: String, error: String, errorCode: Int) {
51
+ failed[id] = error
52
+ }
53
+ }
54
+
55
+ @Before
56
+ fun startServer() {
57
+ server = MockWebServer()
58
+ server.dispatcher = object : Dispatcher() {
59
+ override fun dispatch(request: RecordedRequest): MockResponse {
60
+ requested.add(request.path ?: "")
61
+ // Keep the transfer open until the test lets it finish, so a
62
+ // running download really does occupy its slot
63
+ holdResponses.await(20, TimeUnit.SECONDS)
64
+ return MockResponse().setBody("payload")
65
+ }
66
+ }
67
+ server.start()
68
+ downloader = ResumableDownloader()
69
+ }
70
+
71
+ @After
72
+ fun stopServer() {
73
+ holdResponses.countDown()
74
+ server.shutdown()
75
+ // Other tests must not inherit this test's cap
76
+ ResumableDownloader.setMaxConcurrentTransfers(DownloadConstants.DEFAULT_MAX_PARALLEL_DOWNLOADS)
77
+ }
78
+
79
+ private fun start(id: String) {
80
+ downloader.startDownload(
81
+ id = id,
82
+ url = server.url("/$id").toString(),
83
+ destination = tempFolder.newFile(id).absolutePath,
84
+ headers = emptyMap(),
85
+ listener = listener,
86
+ isAllowedOverMetered = true
87
+ )
88
+ }
89
+
90
+ private fun awaitUntil(what: String, timeoutMs: Long = 5000, condition: () -> Boolean) {
91
+ val deadline = System.currentTimeMillis() + timeoutMs
92
+ while (System.currentTimeMillis() < deadline) {
93
+ if (condition()) return
94
+ Thread.sleep(25)
95
+ }
96
+ throw AssertionError("Timed out waiting for: $what")
97
+ }
98
+
99
+ private fun assertStaysAt(count: Int, what: String) {
100
+ // Give anything that should not have started the chance to prove it did
101
+ Thread.sleep(500)
102
+ assertEquals(what, count, requested.size)
103
+ }
104
+
105
+ @Test
106
+ fun `only maxConcurrentTransfers downloads transfer at once`() {
107
+ ResumableDownloader.setMaxConcurrentTransfers(2)
108
+
109
+ repeat(5) { start("download-$it") }
110
+
111
+ awaitUntil("two transfers to reach the server") { requested.size == 2 }
112
+ assertStaysAt(2, "third download must wait for a slot")
113
+ }
114
+
115
+ @Test
116
+ fun `a waiting download starts when a running one finishes`() {
117
+ ResumableDownloader.setMaxConcurrentTransfers(2)
118
+
119
+ repeat(3) { start("download-$it") }
120
+ awaitUntil("two transfers to reach the server") { requested.size == 2 }
121
+
122
+ // Let the running transfers complete - each one frees its slot
123
+ holdResponses.countDown()
124
+
125
+ awaitUntil("the queued download to start") { requested.size == 3 }
126
+ awaitUntil("every download to complete") { completed.size == 3 }
127
+ }
128
+
129
+ @Test
130
+ fun `a download paused while waiting never starts`() {
131
+ ResumableDownloader.setMaxConcurrentTransfers(1)
132
+
133
+ start("running")
134
+ awaitUntil("the first transfer to reach the server") { requested.size == 1 }
135
+
136
+ start("waiting")
137
+ assertStaysAt(1, "the second download must wait for a slot")
138
+
139
+ // The user pauses it before it ever got a slot
140
+ assertTrue(downloader.pause("waiting"))
141
+
142
+ holdResponses.countDown()
143
+ awaitUntil("the running download to complete") { completed.contains("running") }
144
+
145
+ // Its slot freed, but a paused download must not be started by the queue
146
+ assertStaysAt(1, "a download paused while waiting must not start")
147
+ assertTrue(downloader.isPaused("waiting"))
148
+ }
149
+
150
+ @Test
151
+ fun `a download cancelled while waiting never starts`() {
152
+ ResumableDownloader.setMaxConcurrentTransfers(1)
153
+
154
+ start("running")
155
+ awaitUntil("the first transfer to reach the server") { requested.size == 1 }
156
+
157
+ start("waiting")
158
+ assertStaysAt(1, "the second download must wait for a slot")
159
+
160
+ assertTrue(downloader.cancel("waiting"))
161
+
162
+ holdResponses.countDown()
163
+ awaitUntil("the running download to complete") { completed.contains("running") }
164
+
165
+ assertStaysAt(1, "a cancelled download must not start")
166
+ }
167
+
168
+ @Test
169
+ fun `resuming a paused download goes back through the queue`() {
170
+ ResumableDownloader.setMaxConcurrentTransfers(1)
171
+
172
+ start("running")
173
+ awaitUntil("the first transfer to reach the server") { requested.size == 1 }
174
+
175
+ start("waiting")
176
+ assertTrue(downloader.pause("waiting"))
177
+ assertTrue(downloader.resume("waiting", listener))
178
+
179
+ // The slot is still taken by the running download, so a resume waits too
180
+ assertStaysAt(1, "a resumed download must not jump the queue")
181
+
182
+ holdResponses.countDown()
183
+ awaitUntil("the resumed download to start") { requested.size == 2 }
184
+ }
185
+
186
+ @Test
187
+ fun `the cap does not lose downloads under load`() {
188
+ ResumableDownloader.setMaxConcurrentTransfers(3)
189
+
190
+ repeat(12) { start("download-$it") }
191
+ awaitUntil("the first batch to reach the server") { requested.size == 3 }
192
+
193
+ holdResponses.countDown()
194
+
195
+ awaitUntil("every download to complete", timeoutMs = 20000) { completed.size == 12 }
196
+ assertEquals("no download ran twice", 12, requested.toSet().size)
197
+ assertTrue("no download failed: $failed", failed.isEmpty())
198
+ }
199
+ }
@@ -0,0 +1,159 @@
1
+ package com.eko.uidt
2
+
3
+ import android.app.job.JobInfo
4
+ import android.content.ComponentName
5
+ import android.content.Context
6
+ import android.os.PersistableBundle
7
+ import androidx.test.core.app.ApplicationProvider
8
+ import com.eko.UIDTDownloadJobService
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertNotEquals
11
+ import org.junit.Assert.assertNull
12
+ import org.junit.Before
13
+ import org.junit.Test
14
+ import org.junit.runner.RunWith
15
+ import org.robolectric.RobolectricTestRunner
16
+ import org.robolectric.annotation.Config
17
+
18
+ /**
19
+ * Job IDs used to be `JOB_ID_BASE + hash(configId) % 10000`, and scheduling an ID
20
+ * that already exists replaces the job holding it - so two downloads hashing
21
+ * together silently killed one of each other. These pin the lookup that replaced
22
+ * it: a job is found by the config ID it already carries in its extras.
23
+ */
24
+ @RunWith(RobolectricTestRunner::class)
25
+ @Config(sdk = [34])
26
+ class UIDTJobIdsTest {
27
+
28
+ private val context: Context get() = ApplicationProvider.getApplicationContext()
29
+
30
+ /** Two distinct strings with the same hash code - the collision this fixes. */
31
+ private val colliding = Pair("Aa", "BB")
32
+
33
+ @Before
34
+ fun clearReservations() {
35
+ for (id in listOf(colliding.first, colliding.second, "a", "b")) {
36
+ UIDTJobIds.endReservation(id)
37
+ }
38
+ }
39
+
40
+ private fun downloadJob(jobId: Int, configId: String): JobInfo =
41
+ JobInfo.Builder(jobId, ComponentName(context, UIDTDownloadJobService::class.java))
42
+ .setExtras(PersistableBundle().apply { putString(UIDTConstants.KEY_DOWNLOAD_ID, configId) })
43
+ .setMinimumLatency(1000)
44
+ .build()
45
+
46
+ /** A job belonging to something else in the app - WorkManager, say. */
47
+ private fun foreignJob(jobId: Int): JobInfo =
48
+ JobInfo.Builder(jobId, ComponentName(context, "com.example.SomeOtherService"))
49
+ .setMinimumLatency(1000)
50
+ .build()
51
+
52
+ @Test
53
+ fun `a download's job is found by the config ID in its extras`() {
54
+ val jobs = listOf(downloadJob(12345, "other"), downloadJob(23456, "a"))
55
+
56
+ assertEquals(23456, UIDTJobIds.jobIdFor("a", jobs))
57
+ }
58
+
59
+ @Test
60
+ fun `a download with no job has no ID`() {
61
+ assertNull(UIDTJobIds.jobIdFor("a", listOf(downloadJob(12345, "other"))))
62
+ }
63
+
64
+ @Test
65
+ fun `another component's job is never mistaken for a download`() {
66
+ val jobs = listOf(foreignJob(10001))
67
+
68
+ assertNull(UIDTJobIds.jobIdFor("a", jobs))
69
+ assertNull(UIDTJobIds.configIdOf(jobs.first()))
70
+ }
71
+
72
+ @Test
73
+ fun `colliding downloads reserve different job IDs`() {
74
+ val first = UIDTJobIds.reserveJobId(colliding.first, emptyList())
75
+ val second = UIDTJobIds.reserveJobId(colliding.second, emptyList())
76
+
77
+ assertNotEquals(first, second)
78
+ }
79
+
80
+ @Test
81
+ fun `a reservation is not handed out twice`() {
82
+ val reserved = UIDTJobIds.reserveJobId(colliding.first, emptyList())
83
+
84
+ // The colliding download must not be offered the same ID while the first
85
+ // one is still on its way to the JobScheduler
86
+ assertNotEquals(reserved, UIDTJobIds.reserveJobId(colliding.second, emptyList()))
87
+
88
+ UIDTJobIds.endReservation(colliding.first)
89
+
90
+ // Once the first is scheduled (or was rejected), the ID is free again
91
+ UIDTJobIds.endReservation(colliding.second)
92
+ assertEquals(reserved, UIDTJobIds.reserveJobId(colliding.second, emptyList()))
93
+ }
94
+
95
+ @Test
96
+ fun `a download that already has a job keeps that job's ID`() {
97
+ val jobs = listOf(downloadJob(19999, "a"))
98
+
99
+ // Re-scheduling replaces the existing job instead of adding a second one
100
+ assertEquals(19999, UIDTJobIds.reserveJobId("a", jobs))
101
+ }
102
+
103
+ @Test
104
+ fun `an ID held by a live job is never reserved`() {
105
+ val legacy = UIDTConstants.JOB_ID_BASE + (colliding.first.hashCode() and 0x7FFFFFFF) % 10000
106
+ val jobs = listOf(downloadJob(legacy, "somebody-else"))
107
+
108
+ assertNotEquals(legacy, UIDTJobIds.reserveJobId(colliding.first, jobs))
109
+ }
110
+
111
+ @Test
112
+ fun `an ID held by another component's job is never reserved`() {
113
+ val legacy = UIDTConstants.JOB_ID_BASE + ("a".hashCode() and 0x7FFFFFFF) % 10000
114
+ val jobs = listOf(foreignJob(legacy))
115
+
116
+ // The old hash scheme would have stomped the host app's job here
117
+ assertNotEquals(legacy, UIDTJobIds.reserveJobId("a", jobs))
118
+ }
119
+
120
+ @Test
121
+ fun `a download with no live job reserves its legacy ID`() {
122
+ val legacy = UIDTConstants.JOB_ID_BASE + ("a".hashCode() and 0x7FFFFFFF) % 10000
123
+
124
+ // Nothing else holds it, so the download keeps the ID it always had -
125
+ // including a job scheduled by a version that derived IDs from the hash
126
+ assertEquals(legacy, UIDTJobIds.reserveJobId("a", emptyList()))
127
+ }
128
+
129
+ @Test
130
+ fun `cancelling falls back to the legacy ID when the pending jobs are unreadable`() {
131
+ val legacy = UIDTConstants.JOB_ID_BASE + ("a".hashCode() and 0x7FFFFFFF) % 10000
132
+
133
+ // Cancelling an ID that holds no job is a no-op, so the legacy guess is
134
+ // strictly better than not cancelling at all
135
+ assertEquals(legacy, UIDTJobIds.jobIdToCancel("a", null))
136
+ }
137
+
138
+ @Test
139
+ fun `cancelling uses the live job's ID when it is known`() {
140
+ val jobs = listOf(downloadJob(17777, "a"))
141
+
142
+ assertEquals(17777, UIDTJobIds.jobIdToCancel("a", jobs))
143
+ }
144
+
145
+ @Test
146
+ fun `ourJobs keeps only the library's download jobs`() {
147
+ val jobs = listOf(downloadJob(11111, "a"), foreignJob(11112), downloadJob(11113, "b"))
148
+
149
+ assertEquals(listOf(11111, 11113), UIDTJobIds.ourJobs(jobs).map { it.id })
150
+ }
151
+
152
+ @Test
153
+ fun `IDs stay unique across a full batch of downloads`() {
154
+ val ids = (1..150).map { UIDTJobIds.reserveJobId("download-$it", emptyList()) }
155
+
156
+ assertEquals(150, ids.toSet().size)
157
+ for (i in 1..150) UIDTJobIds.endReservation("download-$i")
158
+ }
159
+ }
@@ -0,0 +1,192 @@
1
+ package com.eko.uidt
2
+
3
+ import android.app.DownloadManager
4
+ import android.app.job.JobInfo
5
+ import android.app.job.JobScheduler
6
+ import android.content.ComponentName
7
+ import android.content.Context
8
+ import androidx.test.core.app.ApplicationProvider
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertFalse
11
+ import org.junit.Assert.assertNotEquals
12
+ import org.junit.Assert.assertNull
13
+ import org.junit.Assert.assertTrue
14
+ import org.junit.Before
15
+ import org.junit.Test
16
+ import org.junit.runner.RunWith
17
+ import org.robolectric.RobolectricTestRunner
18
+ import org.robolectric.annotation.Config
19
+
20
+ /**
21
+ * The scheduling contract of the UIDT path: every download gets its own job, a
22
+ * batch big enough to exhaust the app's job quota degrades instead of crashing,
23
+ * and a job that hasn't started yet is still visible.
24
+ */
25
+ @RunWith(RobolectricTestRunner::class)
26
+ @Config(sdk = [34])
27
+ class UIDTJobManagerTest {
28
+
29
+ private val context: Context get() = ApplicationProvider.getApplicationContext()
30
+ private val jobScheduler: JobScheduler
31
+ get() = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
32
+
33
+ /** Two distinct strings with the same hash code. */
34
+ private val colliding = Pair("Aa", "BB")
35
+
36
+ private var foreignJobId = 500000
37
+
38
+ @Before
39
+ fun clearScheduler() {
40
+ foreignJobId = 500000
41
+ jobScheduler.cancelAll()
42
+ UIDTJobRegistry.activeJobs.clear()
43
+ }
44
+
45
+ private fun schedule(configId: String, startByte: Long = 0, totalBytes: Long = -1): Boolean =
46
+ UIDTJobManager.scheduleDownload(
47
+ context = context,
48
+ configId = configId,
49
+ url = "https://example.com/$configId",
50
+ destination = "/tmp/$configId",
51
+ headers = mapOf("Authorization" to "Bearer $configId"),
52
+ startByte = startByte,
53
+ totalBytes = totalBytes,
54
+ metadata = """{"groupId":"group-1"}""",
55
+ isAllowedOverMetered = true
56
+ )
57
+
58
+ /** Fill the scheduler with jobs belonging to the rest of the app. */
59
+ private fun fillSchedulerWith(count: Int) {
60
+ repeat(count) {
61
+ jobScheduler.schedule(
62
+ JobInfo.Builder(foreignJobId++, ComponentName(context, "com.example.SomeOtherService"))
63
+ .setMinimumLatency(1000)
64
+ .build()
65
+ )
66
+ }
67
+ }
68
+
69
+ private fun scheduledConfigIds(): List<String> =
70
+ jobScheduler.allPendingJobs.mapNotNull { UIDTJobIds.configIdOf(it) }
71
+
72
+ @Test
73
+ fun `scheduling a download creates a job carrying its config ID`() {
74
+ assertTrue(schedule("a"))
75
+
76
+ assertEquals(listOf("a"), scheduledConfigIds())
77
+ val job = jobScheduler.allPendingJobs.single()
78
+ assertEquals("https://example.com/a", job.extras.getString(UIDTConstants.KEY_URL))
79
+ assertTrue(job.isUserInitiated)
80
+ }
81
+
82
+ @Test
83
+ fun `two downloads whose IDs collide each get their own job`() {
84
+ assertTrue(schedule(colliding.first))
85
+ assertTrue(schedule(colliding.second))
86
+
87
+ // The old hash-derived ID would have made the second replace the first
88
+ assertEquals(2, jobScheduler.allPendingJobs.size)
89
+ assertEquals(setOf(colliding.first, colliding.second), scheduledConfigIds().toSet())
90
+ assertNotEquals(
91
+ UIDTJobIds.jobIdFor(colliding.first, jobScheduler.allPendingJobs),
92
+ UIDTJobIds.jobIdFor(colliding.second, jobScheduler.allPendingJobs)
93
+ )
94
+ }
95
+
96
+ @Test
97
+ fun `re-scheduling a download replaces its own job instead of adding one`() {
98
+ assertTrue(schedule("a"))
99
+ val firstJobId = UIDTJobIds.jobIdFor("a", jobScheduler.allPendingJobs)
100
+
101
+ assertTrue(schedule("a", startByte = 4096))
102
+
103
+ assertEquals(1, jobScheduler.allPendingJobs.size)
104
+ assertEquals(firstJobId, UIDTJobIds.jobIdFor("a", jobScheduler.allPendingJobs))
105
+ assertEquals(4096L, jobScheduler.allPendingJobs.single().extras.getLong(UIDTConstants.KEY_START_BYTE))
106
+ }
107
+
108
+ @Test
109
+ fun `a batch of downloads gets a job each`() {
110
+ val ids = (1..40).map { "download-$it" }
111
+ ids.forEach { assertTrue(schedule(it)) }
112
+
113
+ assertEquals(ids.toSet(), scheduledConfigIds().toSet())
114
+ }
115
+
116
+ @Test
117
+ fun `scheduling is refused once the app is out of job slots`() {
118
+ // The quota is app-wide, so somebody else's jobs can exhaust it
119
+ fillSchedulerWith(130)
120
+
121
+ assertFalse("the caller must fall back instead of crashing", schedule("a"))
122
+ assertTrue("no job may be left behind", scheduledConfigIds().isEmpty())
123
+ }
124
+
125
+ @Test
126
+ fun `headroom is kept for the rest of the app`() {
127
+ fillSchedulerWith(100)
128
+
129
+ // Well under the 150-job limit, but past the point where the library
130
+ // stops claiming slots
131
+ assertTrue(schedule("a"))
132
+ fillSchedulerWith(25)
133
+ assertFalse(schedule("b"))
134
+ }
135
+
136
+ @Test
137
+ fun `a download that already has a job can still be rescheduled at the quota`() {
138
+ assertTrue(schedule("a"))
139
+ fillSchedulerWith(130)
140
+
141
+ // Replacing its own job needs no free slot - this is how a resume works
142
+ assertTrue(schedule("a", startByte = 128))
143
+ assertEquals(128L, jobScheduler.allPendingJobs.single { UIDTJobIds.configIdOf(it) == "a" }
144
+ .extras.getLong(UIDTConstants.KEY_START_BYTE))
145
+ }
146
+
147
+ @Test
148
+ fun `a scheduled download is reported as pending with its byte counts`() {
149
+ assertTrue(schedule("a", startByte = 512, totalBytes = 2048))
150
+
151
+ val reported = UIDTJobManager.getScheduledJobs(context).single()
152
+ assertEquals("a", reported.id)
153
+ assertEquals(DownloadManager.STATUS_PENDING, reported.status)
154
+ assertEquals(512L, reported.bytesDownloaded)
155
+ assertEquals(2048L, reported.bytesTotal)
156
+ assertEquals("https://example.com/a", reported.url)
157
+ assertTrue(UIDTJobManager.isScheduledJob(context, "a"))
158
+ }
159
+
160
+ @Test
161
+ fun `only the library's own jobs are reported`() {
162
+ fillSchedulerWith(3)
163
+ assertTrue(schedule("a"))
164
+
165
+ assertEquals(listOf("a"), UIDTJobManager.getScheduledJobs(context).map { it.id })
166
+ assertFalse(UIDTJobManager.isScheduledJob(context, "not-a-download"))
167
+ }
168
+
169
+ @Test
170
+ fun `cancelling a download removes its job and leaves the others alone`() {
171
+ assertTrue(schedule(colliding.first))
172
+ assertTrue(schedule(colliding.second))
173
+
174
+ UIDTJobManager.cancelJob(context, colliding.first)
175
+
176
+ assertEquals(listOf(colliding.second), scheduledConfigIds())
177
+ assertNull(UIDTJobIds.jobIdFor(colliding.first, jobScheduler.allPendingJobs))
178
+ }
179
+
180
+ @Test
181
+ fun `pausing a scheduled download returns what it needs to resume`() {
182
+ assertTrue(schedule("a", startByte = 1024, totalBytes = 8192))
183
+
184
+ val paused = UIDTJobManager.cancelPendingJob(context, "a")
185
+
186
+ assertEquals("https://example.com/a", paused?.url)
187
+ assertEquals(1024L, paused?.startByte)
188
+ assertEquals(8192L, paused?.totalBytes)
189
+ assertEquals("Bearer a", paused?.headers?.get("Authorization"))
190
+ assertTrue("the job must be gone", scheduledConfigIds().isEmpty())
191
+ }
192
+ }