Skip to content

Commit

Permalink
fix: add new workflow to remove old rocketchat sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
tkuzynow committed Feb 12, 2024
1 parent d995e16 commit 40d08c4
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 83 deletions.
3 changes: 1 addition & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -424,11 +424,10 @@
<version>1.2021.16</version>
</dependency>

<!-- MongoDB dependencies -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.11</version>
<version>3.12.14</version>
</dependency>

<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package de.caritas.cob.userservice.api.adapters.rocketchat;

import com.google.common.collect.Lists;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import de.caritas.cob.userservice.api.adapters.rocketchat.model.RocketchatSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.NonNull;
import org.bson.Document;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class RocketChatMongoDbService implements InitializingBean {

@Value("${spring.data.mongodb.rocketchat.uri}")
String mongoUrl;

@Value("${spring.data.mongodb.rocketchat.database}")
String databaseName;

@NonNull MongoClient mongoClient;

public List<RocketchatSession> findInactiveSessions() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection("rocketchat_sessions");
Document sessionInactivityCriteria = sessionInactivityCriteria();
List<RocketchatSession> rocketchatSessions = Lists.newArrayList();
collection
.find(sessionInactivityCriteria)
.forEach(document -> rocketchatSessions.add(new RocketchatSession(document)));
return rocketchatSessions;
}

private Document sessionInactivityCriteria() {
Document closedAt = new Document("closedAt", null);
closedAt.put("lastActivityAt", new Document("$lt", "2021-01-01T00:00:00.000Z"));
return closedAt;
}

@Override
public void afterPropertiesSet() throws Exception {
initializeMongoClient();
}

private void initializeMongoClient() {
if (mongoClient == null) {
mongoClient = MongoClients.create(mongoUrl);
}
}

public void patchClosedAt(RocketchatSession rocketchatSession) {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection("rocketchat_sessions");
Document originalSession =
collection.find(new Document("sessionId", rocketchatSession.getSessionId())).first();

Document patchedDocument = patchDocumentWithClosedAt(rocketchatSession, originalSession);
collection.replaceOne(originalSession, patchedDocument);
}

private Document patchDocumentWithClosedAt(
RocketchatSession rocketchatSession, Document document) {
var patchedDocument = cloneDocument(document);
patchedDocument.put("closedAt", rocketchatSession.getClosedAt());
return patchedDocument;
}

private Document cloneDocument(Document document) {
return new Document(
document.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package de.caritas.cob.userservice.api.adapters.rocketchat.model;

import java.time.Instant;
import java.util.Date;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "rocketchat_sessions")
@Data
public class RocketchatSession {
private Instant closedAt;

private String sessionId;

private String userId;

public RocketchatSession(org.bson.Document document) {
this.sessionId = document.getString("sessionId");
this.userId = document.getString("userId");
Date closedAtNullable = document.getDate("closedAt");
this.closedAt = closedAtNullable != null ? closedAtNullable.toInstant() : null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,12 @@ protected void configure(HttpSecurity http) throws Exception {
.antMatchers("/users/password/change")
.hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT, SINGLE_TENANT_ADMIN, TENANT_ADMIN)
.antMatchers("/users/twoFactorAuth", "/users/2fa/**", "/users/mobile/app/token")
.hasAnyAuthority(SINGLE_TENANT_ADMIN, TENANT_ADMIN, USER_DEFAULT, CONSULTANT_DEFAULT)
.hasAnyAuthority(
SINGLE_TENANT_ADMIN,
TENANT_ADMIN,
USER_DEFAULT,
CONSULTANT_DEFAULT,
RESTRICTED_AGENCY_ADMIN)
.antMatchers("/users/statistics/registration")
.hasAnyAuthority(SINGLE_TENANT_ADMIN, TENANT_ADMIN)
.antMatchers(
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import static de.caritas.cob.userservice.api.workflow.delete.model.DeletionTargetType.ALL;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;

import de.caritas.cob.userservice.api.model.RocketchatSession;
import de.caritas.cob.userservice.api.port.out.RocketchatSessionRepository;
import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatMongoDbService;
import de.caritas.cob.userservice.api.adapters.rocketchat.model.RocketchatSession;
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.time.Instant;
import java.util.ArrayList;
Expand All @@ -22,15 +22,15 @@
@Slf4j
public class CloseInactiveRocketchatSessionsService {

private final @NonNull RocketchatSessionRepository rocketchatSessionRepository;
private final @NonNull RocketChatMongoDbService rocketChatMongoDbService;

private final @NonNull WorkflowErrorMailService workflowErrorMailService;

public void closeInactiveRocketchatSessions() {

List<DeletionWorkflowError> workflowErrors = new ArrayList<>();
try {
List<RocketchatSession> inactiveSessions = rocketchatSessionRepository.findInactiveSessions();
List<RocketchatSession> inactiveSessions = rocketChatMongoDbService.findInactiveSessions();
if (isNotEmpty(inactiveSessions)) {
log.info("Found {} inactive rocketchat sessions.", inactiveSessions.size());
} else {
Expand All @@ -55,7 +55,7 @@ private void closeSession(RocketchatSession rocketchatSession) {
"Closing rocketchat session with id: {} for rcUserId: {}",
rocketchatSession.getSessionId());
rocketchatSession.setClosedAt(Instant.now());
rocketchatSessionRepository.save(rocketchatSession);
rocketChatMongoDbService.patchClosedAt(rocketchatSession);
}

private void sendWorkflowErrorsMail(List<DeletionWorkflowError> workflowErrors) {
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,6 @@ management.health.probes.enabled=true
spring.data.mongodb.uri=mongodb://<USERNAME>:<PASSWORD>@mongodb:27017/rocketchat?directConnection=true
rocketchat.session.inactive.closeWorkflow.enabled=false
rocketchat.session.inactive.closeWorkflow.cron=0 0 2 * * ?

spring.data.mongodb.rocketchat.database=rocketchat
spring.data.mongodb.rocketchat.uri=mongodb://<USERNAME>:<PASSWORD>@mongodb:27017/rocketchat?directConnection=true
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void performDeletionWorkflow_Should_CallDeleteInactiveRocketchatSessionsService(
closeInactiveRocketchatSessionsService, tenantContextProvider);
ReflectionTestUtils.setField(
deleteInactiveRocketchatSessionsScheduler,
"rocketchatSessionInactiveDeleteWorkflowEnabled",
"rocketchatSessionInactiveCloseWorkflowEnabled",
true);
// when
deleteInactiveRocketchatSessionsScheduler.performDeletionWorkflow();
Expand All @@ -42,7 +42,7 @@ void performDeletionWorkflow_Should_CallDeleteInactiveRocketchatSessionsService(
closeInactiveRocketchatSessionsService, tenantContextProvider);
ReflectionTestUtils.setField(
closeInactiveRocketchatSessionsScheduler,
"rocketchatSessionInactiveDeleteWorkflowEnabled",
"rocketchatSessionInactiveCloseWorkflowEnabled",
false);
// when
closeInactiveRocketchatSessionsScheduler.performDeletionWorkflow();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import static org.mockito.Mockito.when;

import com.google.common.collect.Lists;
import de.caritas.cob.userservice.api.model.RocketchatSession;
import de.caritas.cob.userservice.api.port.out.RocketchatSessionRepository;
import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatMongoDbService;
import de.caritas.cob.userservice.api.adapters.rocketchat.model.RocketchatSession;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -21,7 +21,7 @@ class CloseInactiveRocketchatSessionsServiceTest {

@InjectMocks CloseInactiveRocketchatSessionsService closeInactiveRocketchatSessionsService;

@Mock RocketchatSessionRepository rocketchatSessionRepository;
@Mock RocketChatMongoDbService rocketChatMongoDbService;

@Mock WorkflowErrorMailService workflowErrorMailService;

Expand All @@ -30,8 +30,7 @@ class CloseInactiveRocketchatSessionsServiceTest {
@Test
void deleteInactiveRocketchatSessions_Should_CallDeleteInactiveRocketchatSessions() {
// given
when(rocketchatSessionRepository.findInactiveSessions())
.thenReturn(Lists.newArrayList(session));
when(rocketChatMongoDbService.findInactiveSessions()).thenReturn(Lists.newArrayList(session));
// when
closeInactiveRocketchatSessionsService.closeInactiveRocketchatSessions();
// then
Expand All @@ -43,7 +42,7 @@ void deleteInactiveRocketchatSessions_Should_CallDeleteInactiveRocketchatSession
void
deleteInactiveRocketchatSessions_Should_SendWorkflowErrorsIfExceptionCaughtUponSessionDeletion() {
// given
doThrow(IllegalStateException.class).when(rocketchatSessionRepository).findInactiveSessions();
doThrow(IllegalStateException.class).when(rocketChatMongoDbService).findInactiveSessions();
// when
closeInactiveRocketchatSessionsService.closeInactiveRocketchatSessions();
// then
Expand Down

0 comments on commit 40d08c4

Please sign in to comment.