Skip to content

Commit

Permalink
fix(storage): Remove work manager restricted API usage and upgrade li…
Browse files Browse the repository at this point in the history
…b. (#2674)
  • Loading branch information
tylerjroach authored Jan 9, 2024
1 parent 051988a commit 9f1db18
Show file tree
Hide file tree
Showing 7 changed files with 21 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
*/
package com.amplifyframework.logging.cloudwatch.worker

import android.annotation.SuppressLint
import android.content.Context
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.work.CoroutineWorker
import androidx.work.ListenableWorker
import androidx.work.WorkerParameters
import com.google.common.util.concurrent.ListenableFuture
Expand All @@ -28,7 +28,7 @@ internal class CloudwatchRouterWorker(appContext: Context, private val parameter
private val workerClassName =
parameter.inputData.getString(WORKER_CLASS_NAME)
?: throw IllegalArgumentException("Worker class name is missing")
private var delegateWorker: ListenableWorker? = null
private var delegateWorker: CoroutineWorker? = null

companion object {
internal const val WORKER_CLASS_NAME = "WORKER_CLASS_NAME"
Expand Down Expand Up @@ -70,14 +70,8 @@ internal class CloudwatchRouterWorker(appContext: Context, private val parameter
}
}

@SuppressLint("RestrictedApi")
override fun onStopped() {
super.onStopped()
delegateWorker?.stop()
}

@SuppressLint("RestrictedApi")
override fun isRunInForeground(): Boolean {
return delegateWorker?.isRunInForeground ?: false
delegateWorker?.onStopped()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package com.amplifyframework.logging.cloudwatch.worker

import android.content.Context
import androidx.work.ListenableWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import com.amplifyframework.logging.cloudwatch.CloudWatchLogManager
Expand All @@ -30,7 +30,7 @@ internal class CloudwatchWorkerFactory(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker {
): CoroutineWorker {
return when (workerClassName) {
CloudwatchLogsSyncWorker::class.java.simpleName -> {
CloudwatchLogsSyncWorker(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ import java.io.File
import java.lang.Exception
import java.net.SocketException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive

/**
* Base worker to perform transfer file task.
Expand All @@ -74,9 +76,6 @@ internal abstract class BaseTransferWorker(
internal const val PART_RECORD_ID = "PART_RECORD_ID"
internal const val RUN_AS_FOREGROUND_TASK = "RUN_AS_FOREGROUND_TASK"
internal const val WORKER_ID = "WORKER_ID"
private const val OBJECT_TAGS_DELIMITER = "&"
private const val OBJECT_TAG_KEY_VALUE_SEPARATOR = "="
private const val REQUESTER_PAYS = "requester"
private val CANNED_ACL_MAP =
ObjectCannedAcl.values().associateBy { it.value }
internal const val MULTI_PART_UPLOAD_ID = "multipartUploadId"
Expand Down Expand Up @@ -112,10 +111,10 @@ internal abstract class BaseTransferWorker(
}
else -> {
val ex = result.exceptionOrNull()
if (!isStopped) {
if (currentCoroutineContext().isActive) {
logger.error("${this.javaClass.simpleName} failed with exception: ${Log.getStackTraceString(ex)}")
}
if (isRetryableError(ex)) {
if (!currentCoroutineContext().isActive && isRetryableError(ex)) {
Result.retry()
} else {
transferStatusUpdater.updateOnError(transferRecord.id, Exception(ex))
Expand Down Expand Up @@ -151,8 +150,7 @@ internal abstract class BaseTransferWorker(
}

private fun isRetryableError(e: Throwable?): Boolean {
return isStopped ||
!isNetworkAvailable(applicationContext) ||
return !isNetworkAvailable(applicationContext) ||
runAttemptCount < maxRetryCount ||
e is CancellationException ||
// SocketException is thrown when download is terminated due to network disconnection.
Expand Down Expand Up @@ -200,7 +198,7 @@ internal abstract class BaseTransferWorker(
return false
}

internal suspend fun createPutObjectRequest(
internal fun createPutObjectRequest(
transferRecord: TransferRecord,
progressListener: ProgressListener?
): PutObjectRequest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ import com.amplifyframework.storage.s3.transfer.TransferStatusUpdater
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext

/**
Expand All @@ -48,7 +49,6 @@ internal class DownloadWorker(

private lateinit var downloadProgressListener: DownloadProgressListener
private val defaultBufferSize = 8192L
val coroutineScope = CoroutineScope(Dispatchers.IO)
override suspend fun performWork(): Result {
s3.withConfig {
enableAccelerate = transferRecord.useAccelerateEndpoint == 1
Expand Down Expand Up @@ -104,7 +104,7 @@ internal class DownloadWorker(
var totalRead = 0L
BufferedOutputStream(fileOutputStream).use { fileOutput ->
val copied = 0L
while (!isStopped) {
while (currentCoroutineContext().isActive) {
val remaining = limit - copied
if (remaining == 0L) break
val readBytes =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import com.amplifyframework.storage.s3.transfer.TransferDB
import com.amplifyframework.storage.s3.transfer.TransferStatusUpdater
import com.amplifyframework.storage.s3.transfer.UploadProgressListenerInterceptor
import java.io.File
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive

/**
* Worker to upload a part for multipart upload
Expand All @@ -43,7 +45,7 @@ internal class PartUploadTransferWorker(
override var maxRetryCount = 3

override suspend fun performWork(): Result {
if (isStopped) {
if (!currentCoroutineContext().isActive) {
return Result.retry()
}
transferStatusUpdater.updateTransferState(transferRecord.mainUploadId, TransferState.IN_PROGRESS)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

package com.amplifyframework.storage.s3.transfer.worker

import android.annotation.SuppressLint
import android.content.Context
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.work.ListenableWorker
Expand All @@ -29,8 +28,7 @@ import java.lang.IllegalStateException
/**
* Worker to route transfer WorkRequest to appropriate WorkerFactory
*/
@SuppressLint("RestrictedApi")
internal class RouterWorker constructor(
internal class RouterWorker(
appContext: Context,
private val parameter: WorkerParameters
) : ListenableWorker(appContext, parameter) {
Expand All @@ -45,7 +43,7 @@ internal class RouterWorker constructor(
?: throw IllegalArgumentException("Worker class name is missing")
private val workerId = parameter.inputData.getString(BaseTransferWorker.WORKER_ID)

private var delegateWorker: ListenableWorker? = null
private var delegateWorker: BaseTransferWorker? = null

companion object {
internal const val WORKER_CLASS_NAME = "WORKER_CLASS_NAME"
Expand Down Expand Up @@ -86,15 +84,9 @@ internal class RouterWorker constructor(
}
}

@SuppressLint("RestrictedApi")
override fun onStopped() {
super.onStopped()
logger.debug("onStopped for $id")
delegateWorker?.stop()
}

@SuppressLint("RestrictedApi")
override fun isRunInForeground(): Boolean {
return delegateWorker?.isRunInForeground ?: false
delegateWorker?.onStopped()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package com.amplifyframework.storage.s3.transfer.worker

import android.content.Context
import androidx.work.ListenableWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import aws.sdk.kotlin.services.s3.S3Client
Expand All @@ -34,7 +33,7 @@ internal class TransferWorkerFactory(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker {
): BaseTransferWorker {
when (workerClassName) {
DownloadWorker::class.java.name ->
return DownloadWorker(
Expand Down

0 comments on commit 9f1db18

Please sign in to comment.