|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 ETH Zürich, IT Services |
| 3 | + * |
| 4 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 5 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 6 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 7 | + */ |
| 8 | + |
| 9 | +package ch.ethz.seb.sps.server.servicelayer.impl; |
| 10 | + |
| 11 | +import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo; |
| 12 | + |
| 13 | +import java.time.Duration; |
| 14 | +import java.util.Collection; |
| 15 | +import java.util.List; |
| 16 | +import java.util.Map; |
| 17 | +import java.util.concurrent.ConcurrentHashMap; |
| 18 | +import java.util.stream.Collectors; |
| 19 | + |
| 20 | +import ch.ethz.seb.sps.server.ServiceConfig; |
| 21 | +import ch.ethz.seb.sps.server.ServiceInit; |
| 22 | +import ch.ethz.seb.sps.server.datalayer.batis.custommappers.ScreenshotMapper; |
| 23 | +import ch.ethz.seb.sps.server.datalayer.batis.mapper.ScreenshotDataLiveCacheRecordDynamicSqlSupport; |
| 24 | +import ch.ethz.seb.sps.server.datalayer.batis.mapper.ScreenshotDataLiveCacheRecordMapper; |
| 25 | +import ch.ethz.seb.sps.server.datalayer.batis.mapper.ScreenshotDataRecordMapper; |
| 26 | +import ch.ethz.seb.sps.server.datalayer.batis.model.ScreenshotDataLiveCacheRecord; |
| 27 | +import ch.ethz.seb.sps.server.datalayer.dao.ScreenshotDataLiveCacheDAO; |
| 28 | +import ch.ethz.seb.sps.server.datalayer.dao.SessionDAO; |
| 29 | +import ch.ethz.seb.sps.server.servicelayer.LiveProctoringCacheService; |
| 30 | +import ch.ethz.seb.sps.utils.Result; |
| 31 | +import org.apache.ibatis.binding.MapperRegistry; |
| 32 | +import org.apache.ibatis.session.ExecutorType; |
| 33 | +import org.apache.ibatis.session.SqlSessionFactory; |
| 34 | +import org.joda.time.DateTime; |
| 35 | +import org.joda.time.DateTimeZone; |
| 36 | +import org.mybatis.dynamic.sql.update.UpdateDSL; |
| 37 | +import org.mybatis.spring.SqlSessionTemplate; |
| 38 | +import org.slf4j.Logger; |
| 39 | +import org.slf4j.LoggerFactory; |
| 40 | +import org.springframework.beans.factory.annotation.Qualifier; |
| 41 | +import org.springframework.beans.factory.annotation.Value; |
| 42 | +import org.springframework.context.annotation.Lazy; |
| 43 | +import org.springframework.scheduling.TaskScheduler; |
| 44 | +import org.springframework.stereotype.Component; |
| 45 | +import org.springframework.transaction.PlatformTransactionManager; |
| 46 | +import org.springframework.transaction.TransactionDefinition; |
| 47 | +import org.springframework.transaction.TransactionException; |
| 48 | +import org.springframework.transaction.support.TransactionTemplate; |
| 49 | + |
| 50 | +@Lazy |
| 51 | +@Component |
| 52 | +public class LiveProctoringCacheServiceImpl implements LiveProctoringCacheService { |
| 53 | + |
| 54 | + private static final Logger log = LoggerFactory.getLogger(LiveProctoringCacheServiceImpl.class); |
| 55 | + public static final Logger INIT_LOGGER = LoggerFactory.getLogger("SERVICE_INIT"); |
| 56 | + |
| 57 | + private final TaskScheduler taskScheduler; |
| 58 | + private final long batchInterval; |
| 59 | + |
| 60 | + private final SqlSessionFactory sqlSessionFactory; |
| 61 | + private final TransactionTemplate transactionTemplate; |
| 62 | + private final ScreenshotDataLiveCacheDAO screenshotDataLiveCacheDAO; |
| 63 | + private final SessionDAO sessionDAO; |
| 64 | + |
| 65 | + private SqlSessionTemplate sqlSessionTemplate; |
| 66 | + private ScreenshotDataLiveCacheRecordMapper screenshotDataLiveCacheRecordMapper; |
| 67 | + |
| 68 | + |
| 69 | + private final Map<String, Long> cache = new ConcurrentHashMap<>(); |
| 70 | + |
| 71 | + public LiveProctoringCacheServiceImpl( |
| 72 | + final SqlSessionFactory sqlSessionFactory, |
| 73 | + final PlatformTransactionManager transactionManager, |
| 74 | + final ScreenshotDataLiveCacheDAO screenshotDataLiveCacheDAO, |
| 75 | + final SessionDAO sessionDAO, |
| 76 | + @Qualifier(value = ServiceConfig.SCREENSHOT_STORE_API_EXECUTOR) final TaskScheduler taskScheduler, |
| 77 | + @Value("${sps.data.store.batch.interval:1000}") final long batchInterval) { |
| 78 | + |
| 79 | + this.sqlSessionFactory = sqlSessionFactory; |
| 80 | + this.transactionTemplate = new TransactionTemplate(transactionManager); |
| 81 | + this.screenshotDataLiveCacheDAO = screenshotDataLiveCacheDAO; |
| 82 | + this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); |
| 83 | + this.sessionDAO = sessionDAO; |
| 84 | + this.taskScheduler = taskScheduler; |
| 85 | + this.batchInterval = batchInterval; |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | + @Override |
| 90 | + public void init() { |
| 91 | + |
| 92 | + INIT_LOGGER.info("---->"); |
| 93 | + INIT_LOGGER.info("----> Initialize Live Proctoring Cache Service"); |
| 94 | + INIT_LOGGER.info("---->"); |
| 95 | + |
| 96 | + try { |
| 97 | + this.sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory, ExecutorType.BATCH); |
| 98 | + |
| 99 | + final MapperRegistry mapperRegistry = this.sqlSessionTemplate.getConfiguration().getMapperRegistry(); |
| 100 | + final Collection<Class<?>> mappers = mapperRegistry.getMappers(); |
| 101 | + if (!mappers.contains(ScreenshotMapper.class)) { |
| 102 | + mapperRegistry.addMapper(ScreenshotMapper.class); |
| 103 | + } |
| 104 | + if (!mappers.contains(ScreenshotDataRecordMapper.class)) { |
| 105 | + mapperRegistry.addMapper(ScreenshotDataRecordMapper.class); |
| 106 | + } |
| 107 | + this.screenshotDataLiveCacheRecordMapper = this.sqlSessionTemplate.getMapper(ScreenshotDataLiveCacheRecordMapper.class); |
| 108 | + |
| 109 | + this.taskScheduler.scheduleWithFixedDelay( |
| 110 | + this::updateCache, |
| 111 | + DateTime.now(DateTimeZone.UTC).toDate().toInstant(), |
| 112 | + Duration.ofMillis(this.batchInterval)); |
| 113 | + |
| 114 | + |
| 115 | + } catch (Exception e) { |
| 116 | + ServiceInit.INIT_LOGGER.error("----> Live Proctoring Cache Service : failed to initialized", e); |
| 117 | + throw e; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + @Override |
| 122 | + public Long getLatestSSDataId(final String sessionUUID) { |
| 123 | + return cache.get(sessionUUID); |
| 124 | + } |
| 125 | + |
| 126 | + @Override |
| 127 | + public Result<String> createCacheSlot(final String sessionUUID) { |
| 128 | + return screenshotDataLiveCacheDAO.createCacheEntry(sessionUUID); |
| 129 | + } |
| 130 | + |
| 131 | + @Override |
| 132 | + public Result<String> deleteCacheSlot(final String sessionUUID) { |
| 133 | + return screenshotDataLiveCacheDAO.deleteCacheEntry(sessionUUID); |
| 134 | + } |
| 135 | + |
| 136 | + @Override |
| 137 | + public void updateCacheStore(final Collection<ScreenshotQueueData> batch) { |
| 138 | + try { |
| 139 | + |
| 140 | + this.transactionTemplate.executeWithoutResult(status -> { |
| 141 | + |
| 142 | + batch.forEach(data -> { |
| 143 | + if (data.record.getId() != null) { |
| 144 | + UpdateDSL.updateWithMapper( |
| 145 | + screenshotDataLiveCacheRecordMapper::update, |
| 146 | + ScreenshotDataLiveCacheRecordDynamicSqlSupport.screenshotDataLiveCacheRecord) |
| 147 | + .set(ScreenshotDataLiveCacheRecordDynamicSqlSupport.idLatestSsd).equalTo(data.record.getId()) |
| 148 | + .where(ScreenshotDataLiveCacheRecordDynamicSqlSupport.sessionUuid, isEqualTo(data.record.getSessionUuid())) |
| 149 | + .build() |
| 150 | + .execute(); |
| 151 | + } |
| 152 | + }); |
| 153 | + this.sqlSessionTemplate.flushStatements(); |
| 154 | + |
| 155 | + }); |
| 156 | + |
| 157 | + } catch (final TransactionException te) { |
| 158 | + log.error("Failed to batch update screenshot data live cache store. Transaction has failed. Cause: {}", te.getMessage()); |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + @Override |
| 163 | + public void cleanup() { |
| 164 | + try { |
| 165 | + |
| 166 | + List<String> closedSession = sessionDAO |
| 167 | + .getAllClosedSessionsIn(cache.keySet()) |
| 168 | + .getOrThrow(); |
| 169 | + |
| 170 | + screenshotDataLiveCacheDAO |
| 171 | + .deleteAll(closedSession) |
| 172 | + .getOrThrow(); |
| 173 | + |
| 174 | + } catch (Exception e) { |
| 175 | + log.error("Failed to cleanup cache: ", e); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + private void updateCache() { |
| 180 | + try { |
| 181 | + |
| 182 | + Map<String, Long> newValues = screenshotDataLiveCacheDAO |
| 183 | + .getAll() |
| 184 | + .getOrThrow() |
| 185 | + .stream() |
| 186 | + .collect(Collectors.toMap( |
| 187 | + ScreenshotDataLiveCacheRecord::getSessionUuid, |
| 188 | + ScreenshotDataLiveCacheRecord::getIdLatestSsd |
| 189 | + )); |
| 190 | + |
| 191 | + cache.putAll(newValues); |
| 192 | + |
| 193 | + } catch (Exception e) { |
| 194 | + log.error("Failed to update cache: ", e); |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments