Skip to content

Adding deleteModel logging and retrieve download success events. #2409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -460,15 +460,17 @@ public Task<Void> deleteDownloadedModel(@NonNull String modelName) {
executor.execute(
() -> {
// remove all files associated with this model and then clean up model references.
deleteModelDetails(modelName);
boolean isSuccessful = deleteModelDetails(modelName);
taskCompletionSource.setResult(null);
eventLogger.logDeleteModel(isSuccessful);
});
return taskCompletionSource.getTask();
}

private void deleteModelDetails(@NonNull String modelName) {
fileManager.deleteAllModels(modelName);
private boolean deleteModelDetails(@NonNull String modelName) {
boolean isSuccessful = fileManager.deleteAllModels(modelName);
sharedPreferencesUtil.clearModelDetails(modelName);
return isSuccessful;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,8 @@ private Task<CustomModel> fetchDownloadDetails(String modelName, HttpURLConnecti
modelName,
httpResponseCode,
"Too many requests to server please wait before trying again.",
FirebaseMlException.INVALID_ARGUMENT);
case HttpURLConnection.HTTP_SERVER_ERROR:
FirebaseMlException.RESOURCE_EXHAUSTED);
case HttpURLConnection.HTTP_INTERNAL_ERROR:
return setAndLogException(
modelName,
httpResponseCode,
Expand All @@ -240,6 +240,17 @@ private Task<CustomModel> fetchDownloadDetails(String modelName, HttpURLConnecti
modelName,
errorMessage),
FirebaseMlException.INTERNAL);
case HttpURLConnection.HTTP_UNAUTHORIZED:
case HttpURLConnection.HTTP_FORBIDDEN:
return setAndLogException(
modelName,
httpResponseCode,
String.format(
Locale.getDefault(),
"Issue while fetching model (%s); error message: %s",
modelName,
errorMessage),
FirebaseMlException.PERMISSION_DENIED);
default:
return setAndLogException(
modelName,
Expand Down Expand Up @@ -322,10 +333,18 @@ private Task<CustomModel> readCustomModelResponse(
inputStream.close();

if (!downloadUrl.isEmpty() && expireTime > 0L) {
return Tasks.forResult(
new CustomModel(modelName, modelHash, fileSize, downloadUrl, expireTime));
CustomModel model = new CustomModel(modelName, modelHash, fileSize, downloadUrl, expireTime);
eventLogger.logModelInfoRetrieverSuccess(model);
return Tasks.forResult(model);
}
return Tasks.forResult(null);
eventLogger.logDownloadFailureWithReason(
new CustomModel(modelName, modelHash, 0, 0L),
false,
ErrorCode.MODEL_INFO_DOWNLOAD_CONNECTION_FAILED.getValue());
return Tasks.forException(
new FirebaseMlException(
"Model info could not be extracted from download response.",
FirebaseMlException.INTERNAL));
}

private static InputStream maybeUnGzip(InputStream input, String contentEncoding)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.google.firebase.encoders.annotations.Encodable;
import com.google.firebase.encoders.json.JsonDataEncoderBuilder;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.EventName;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.ModelDownloadLogEvent.ModelOptions.ModelInfo.ModelType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -59,7 +60,8 @@ public static Builder builder() {
public enum EventName {
UNKNOWN_EVENT(0),
MODEL_DOWNLOAD(100),
MODEL_UPDATE(101);
MODEL_UPDATE(101),
REMOTE_MODEL_DELETE_ON_DEVICE(252);
private static final SparseArray<EventName> valueMap = new SparseArray<>();

private final int value;
Expand All @@ -68,6 +70,7 @@ public enum EventName {
valueMap.put(0, UNKNOWN_EVENT);
valueMap.put(100, MODEL_DOWNLOAD);
valueMap.put(101, MODEL_UPDATE);
valueMap.put(252, REMOTE_MODEL_DELETE_ON_DEVICE);
}

EventName(int value) {
Expand Down Expand Up @@ -128,6 +131,9 @@ public abstract static class Builder {
@Nullable
public abstract ModelDownloadLogEvent getModelDownloadLogEvent();

@Nullable
public abstract DeleteModelLogEvent getDeleteModelLogEvent();

@NonNull
protected abstract Builder toBuilder();

Expand Down Expand Up @@ -192,6 +198,7 @@ public int getValue() {
public enum DownloadStatus {
UNKNOWN_STATUS(0),
EXPLICITLY_REQUESTED(1),
MODEL_INFO_RETRIEVAL_SUCCEEDED(3),
MODEL_INFO_RETRIEVAL_FAILED(4),
SCHEDULED(5),
DOWNLOADING(6),
Expand All @@ -205,6 +212,7 @@ public enum DownloadStatus {
static {
valueMap.put(0, UNKNOWN_STATUS);
valueMap.put(1, EXPLICITLY_REQUESTED);
valueMap.put(3, MODEL_INFO_RETRIEVAL_SUCCEEDED);
valueMap.put(4, MODEL_INFO_RETRIEVAL_FAILED);
valueMap.put(5, SCHEDULED);
valueMap.put(6, DOWNLOADING);
Expand Down Expand Up @@ -327,6 +335,34 @@ public abstract static class Builder {
}
}

@AutoValue
public abstract static class DeleteModelLogEvent {
@NonNull
public static Builder builder() {
return new AutoValue_FirebaseMlLogEvent_DeleteModelLogEvent.Builder()
.setModelType(ModelType.CUSTOM)
.setIsSuccessful(true);
}

@ModelType
public abstract int getModelType();

public abstract boolean getIsSuccessful();

/** Builder for {@link DeleteModelLogEvent}. */
@AutoValue.Builder
public abstract static class Builder {
@NonNull
public abstract Builder setModelType(@ModelType int value);

@NonNull
public abstract Builder setIsSuccessful(boolean value);

@NonNull
public abstract DeleteModelLogEvent build();
}
}

@AutoValue.Builder
public abstract static class Builder {

Expand All @@ -339,6 +375,9 @@ public abstract static class Builder {
@Nullable
public abstract Builder setModelDownloadLogEvent(@Nullable ModelDownloadLogEvent value);

@Nullable
public abstract Builder setDeleteModelLogEvent(@Nullable DeleteModelLogEvent value);

@NonNull
public abstract FirebaseMlLogEvent build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.google.firebase.FirebaseApp;
import com.google.firebase.ml.modeldownloader.BuildConfig;
import com.google.firebase.ml.modeldownloader.CustomModel;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.DeleteModelLogEvent;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.EventName;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.ModelDownloadLogEvent;
import com.google.firebase.ml.modeldownloader.internal.FirebaseMlLogEvent.ModelDownloadLogEvent.DownloadStatus;
Expand Down Expand Up @@ -96,6 +97,16 @@ void logModelInfoRetrieverFailure(CustomModel model, ErrorCode errorCode) {
logModelInfoRetrieverFailure(model, errorCode, NO_FAILURE_VALUE);
}

void logModelInfoRetrieverSuccess(CustomModel model) {
logDownloadEvent(
model,
ErrorCode.NO_ERROR,
false,
/* shouldLogExactDownloadTime= */ false,
DownloadStatus.MODEL_INFO_RETRIEVAL_SUCCEEDED,
FirebaseMlLogEvent.NO_INT_VALUE);
}

void logModelInfoRetrieverFailure(CustomModel model, ErrorCode errorCode, int httpResponseCode) {
logDownloadEvent(
model,
Expand Down Expand Up @@ -148,6 +159,25 @@ private boolean isStatsLoggingEnabled() {
return sharedPreferencesUtil.getCustomModelStatsCollectionFlag();
}

public void logDeleteModel(boolean success) {
if (!isStatsLoggingEnabled()) {
return;
}

try {
eventSender.sendEvent(
FirebaseMlLogEvent.builder()
.setDeleteModelLogEvent(
DeleteModelLogEvent.builder().setIsSuccessful(success).build())
.setEventName(EventName.REMOTE_MODEL_DELETE_ON_DEVICE)
.setSystemInfo(getSystemInfo())
.build());
} catch (RuntimeException e) {
// Swallow the exception since logging should not break the SDK usage
Log.e(TAG, "Exception thrown from the logging side", e);
}
}

private void logDownloadEvent(
CustomModel customModel,
ErrorCode errorCode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ public synchronized void deleteOldModels(
* destination for a model in this method.
*/
@WorkerThread
public synchronized void deleteAllModels(@NonNull String modelName) {
public synchronized boolean deleteAllModels(@NonNull String modelName) {
File modelFolder = getModelDirUnsafe(modelName);
deleteRecursively(modelFolder);
return deleteRecursively(modelFolder);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ public void listDownloadedModels_returnsModelList() throws Exception {
@Test
public void deleteDownloadedModel() throws Exception {
doNothing().when(mockPrefs).clearModelDetails(eq(MODEL_NAME));
doNothing().when(mockFileManager).deleteAllModels(eq(MODEL_NAME));
when(mockFileManager.deleteAllModels(eq(MODEL_NAME))).thenReturn(true);

TestOnCompleteListener<Void> onCompleteListener = new TestOnCompleteListener<>();
Task<Void> task = firebaseModelDownloader.deleteDownloadedModel(MODEL_NAME);
Expand All @@ -749,6 +749,7 @@ public void deleteDownloadedModel() throws Exception {
assertThat(task.isComplete()).isTrue();
verify(mockPrefs, times(1)).clearModelDetails(eq(MODEL_NAME));
verify(mockFileManager, times(1)).deleteAllModels(eq(MODEL_NAME));
verify(mockEventLogger, times(1)).logDeleteModel(eq(true));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,89 @@ public void downloadService_badRequest() {
eq(HttpURLConnection.HTTP_BAD_REQUEST));
}

@Test
public void downloadService_forbidden() {
String downloadPath =
String.format(CustomModelDownloadService.DOWNLOAD_MODEL_REGEX, "", PROJECT_ID, MODEL_NAME);
stubFor(
get(urlEqualTo(downloadPath))
.withHeader(
CustomModelDownloadService.INSTALLATIONS_AUTH_TOKEN_HEADER,
equalTo(INSTALLATION_TOKEN))
.withHeader(
CustomModelDownloadService.CONTENT_TYPE,
equalTo(CustomModelDownloadService.APPLICATION_JSON))
.withHeader(CustomModelDownloadService.IF_NONE_MATCH_HEADER_KEY, equalTo(MODEL_HASH))
.willReturn(
aResponse()
.withStatus(HttpURLConnection.HTTP_FORBIDDEN)
.withBody(
"{\"status\":\"PERMISSION_DENIED\",\"message\":\"Request not valid\"}")));

CustomModelDownloadService service =
new CustomModelDownloadService(
installationsApiMock, directExecutor, API_KEY, TEST_ENDPOINT, mockEventLogger);

Task<CustomModel> modelTask = service.getCustomModelDetails(PROJECT_ID, MODEL_NAME, MODEL_HASH);

Assert.assertTrue(modelTask.getException() instanceof FirebaseMlException);
Assert.assertEquals(
((FirebaseMlException) modelTask.getException()).getCode(),
FirebaseMlException.PERMISSION_DENIED);

WireMock.verify(
getRequestedFor(urlEqualTo(downloadPath))
.withHeader(
CustomModelDownloadService.INSTALLATIONS_AUTH_TOKEN_HEADER,
equalTo(INSTALLATION_TOKEN)));
verify(mockEventLogger, times(1))
.logModelInfoRetrieverFailure(
any(),
eq(ErrorCode.MODEL_INFO_DOWNLOAD_UNSUCCESSFUL_HTTP_STATUS),
eq(HttpURLConnection.HTTP_FORBIDDEN));
}

@Test
public void downloadService_internalError() {
String downloadPath =
String.format(CustomModelDownloadService.DOWNLOAD_MODEL_REGEX, "", PROJECT_ID, MODEL_NAME);
stubFor(
get(urlEqualTo(downloadPath))
.withHeader(
CustomModelDownloadService.INSTALLATIONS_AUTH_TOKEN_HEADER,
equalTo(INSTALLATION_TOKEN))
.withHeader(
CustomModelDownloadService.CONTENT_TYPE,
equalTo(CustomModelDownloadService.APPLICATION_JSON))
.withHeader(CustomModelDownloadService.IF_NONE_MATCH_HEADER_KEY, equalTo(MODEL_HASH))
.willReturn(
aResponse()
.withStatus(HttpURLConnection.HTTP_INTERNAL_ERROR)
.withBody(
"{\"status\":\"INTERNAL\",\"message\":\"Request cannot reach server\"}")));

CustomModelDownloadService service =
new CustomModelDownloadService(
installationsApiMock, directExecutor, API_KEY, TEST_ENDPOINT, mockEventLogger);

Task<CustomModel> modelTask = service.getCustomModelDetails(PROJECT_ID, MODEL_NAME, MODEL_HASH);

Assert.assertTrue(modelTask.getException() instanceof FirebaseMlException);
Assert.assertEquals(
((FirebaseMlException) modelTask.getException()).getCode(), FirebaseMlException.INTERNAL);

WireMock.verify(
getRequestedFor(urlEqualTo(downloadPath))
.withHeader(
CustomModelDownloadService.INSTALLATIONS_AUTH_TOKEN_HEADER,
equalTo(INSTALLATION_TOKEN)));
verify(mockEventLogger, times(1))
.logModelInfoRetrieverFailure(
any(),
eq(ErrorCode.MODEL_INFO_DOWNLOAD_UNSUCCESSFUL_HTTP_STATUS),
eq(HttpURLConnection.HTTP_INTERNAL_ERROR));
}

@Test
public void downloadService_tooManyRequest() {
String downloadPath =
Expand Down Expand Up @@ -357,7 +440,7 @@ public void downloadService_tooManyRequest() {
Assert.assertTrue(modelTask.getException() instanceof FirebaseMlException);
Assert.assertEquals(
((FirebaseMlException) modelTask.getException()).getCode(),
FirebaseMlException.INVALID_ARGUMENT);
FirebaseMlException.RESOURCE_EXHAUSTED);

WireMock.verify(
getRequestedFor(urlEqualTo(downloadPath))
Expand Down Expand Up @@ -396,7 +479,8 @@ public void downloadService_authenticationIssue() {

Assert.assertTrue(modelTask.getException() instanceof FirebaseMlException);
Assert.assertEquals(
((FirebaseMlException) modelTask.getException()).getCode(), FirebaseMlException.INTERNAL);
((FirebaseMlException) modelTask.getException()).getCode(),
FirebaseMlException.PERMISSION_DENIED);
Assert.assertTrue(
modelTask
.getException()
Expand Down
Loading