1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ondevicepersonalization.services.serviceflow; 18 19 import com.android.internal.annotations.VisibleForTesting; 20 import com.android.ondevicepersonalization.services.OnDevicePersonalizationExecutors; 21 22 import java.util.concurrent.Executors; 23 24 /** Orchestrator that handles the scheduling of all service flows. */ 25 public class ServiceFlowOrchestrator { 26 ServiceFlowOrchestrator()27 ServiceFlowOrchestrator() {} 28 29 private static class ServiceFlowOrchestratorLazyInstanceHolder { 30 static final ServiceFlowOrchestrator LAZY_INSTANCE = 31 new ServiceFlowOrchestrator(); 32 } 33 34 /** Returns the global ServiceFlowOrchestrator. */ getInstance()35 public static ServiceFlowOrchestrator getInstance() { 36 return ServiceFlowOrchestratorLazyInstanceHolder.LAZY_INSTANCE; 37 } 38 39 /** Schedules a given service flow task with the orchestrator. */ schedule(ServiceFlowType serviceFlowType, Object... args)40 public void schedule(ServiceFlowType serviceFlowType, Object... args) { 41 ServiceFlow serviceFlow = ServiceFlowFactory.createInstance(serviceFlowType, args); 42 43 ServiceFlowTask serviceFlowTask = 44 new ServiceFlowTask(serviceFlowType, serviceFlow); 45 46 var unused = switch (serviceFlowType.getPriority()) { 47 case HIGH -> OnDevicePersonalizationExecutors.getHighPriorityBackgroundExecutor() 48 .submit(serviceFlowTask::run); 49 case NORMAL -> OnDevicePersonalizationExecutors.getBackgroundExecutor() 50 .submit(serviceFlowTask::run); 51 case LOW -> OnDevicePersonalizationExecutors.getLowPriorityBackgroundExecutor() 52 .submit(serviceFlowTask::run); 53 }; 54 } 55 56 /** Schedules a given service flow task with the orchestrator for testing only. */ 57 @VisibleForTesting scheduleForTest(ServiceFlowType serviceFlowType, Object... args)58 public void scheduleForTest(ServiceFlowType serviceFlowType, Object... args) { 59 ServiceFlow serviceFlow = ServiceFlowFactory.createInstanceForTest(serviceFlowType, args); 60 61 ServiceFlowTask serviceFlowTask = new ServiceFlowTask(serviceFlowType, serviceFlow); 62 Executors.newSingleThreadExecutor().submit(serviceFlowTask::run); 63 } 64 } 65