Skip to content
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
25 changes: 25 additions & 0 deletions src/main/java/com/augment/cbsa/config/CbsaAsyncConfig.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.augment.cbsa.config;

import com.augment.cbsa.service.CreditAgencyDelayExecutor;
import com.augment.cbsa.service.CreditAgencyDelayGenerator;
import com.augment.cbsa.service.CreditAgencyScoreGenerator;
import java.time.Clock;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.VirtualThreadTaskExecutor;
Expand All @@ -16,6 +20,27 @@ VirtualThreadTaskExecutor creditAgencyExecutor() {
return new VirtualThreadTaskExecutor("credit-agency-");
}

@Bean
CreditAgencyDelayGenerator creditAgencyDelayGenerator() {
return agency -> java.time.Duration.ofSeconds(ThreadLocalRandom.current().nextLong(
agency.minimumDelaySeconds(),
agency.maximumDelaySecondsExclusive()
));
}

@Bean
CreditAgencyScoreGenerator creditAgencyScoreGenerator() {
// Mirror the COBOL COMPUTE into an integer PIC 999 field: nextInt(1, 999)
// yields 1..998, matching the source program's effective upper bound once
// the fractional RANDOM result is truncated into the receiving integer.
return (agency, request) -> ThreadLocalRandom.current().nextInt(1, 999);
}

@Bean
CreditAgencyDelayExecutor creditAgencyDelayExecutor() {
return duration -> Thread.sleep(duration);
}

@Bean
Clock systemClock() {
return Clock.systemUTC();
Expand Down
59 changes: 59 additions & 0 deletions src/main/java/com/augment/cbsa/domain/CreditAgency.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.augment.cbsa.domain;

import java.util.Arrays;

public enum CreditAgency {

CRDTAGY1(1, "CRDTAGY1", "CIPA", 1, 3),
CRDTAGY2(2, "CRDTAGY2", "CIPB", 1, 3),
CRDTAGY3(3, "CRDTAGY3", "CIPC", 1, 3),
CRDTAGY4(4, "CRDTAGY4", "CIPD", 1, 3),
CRDTAGY5(5, "CRDTAGY5", "CIPE", 1, 3);

private final int agencyNumber;
private final String programName;
private final String containerName;
private final int minimumDelaySeconds;
private final int maximumDelaySecondsExclusive;

CreditAgency(
int agencyNumber,
String programName,
String containerName,
int minimumDelaySeconds,
int maximumDelaySecondsExclusive
) {
this.agencyNumber = agencyNumber;
this.programName = programName;
this.containerName = containerName;
this.minimumDelaySeconds = minimumDelaySeconds;
this.maximumDelaySecondsExclusive = maximumDelaySecondsExclusive;
}

public int agencyNumber() {
return agencyNumber;
}

public String programName() {
return programName;
}

public String containerName() {
return containerName;
}

public int minimumDelaySeconds() {
return minimumDelaySeconds;
}

public int maximumDelaySecondsExclusive() {
return maximumDelaySecondsExclusive;
}

public static CreditAgency fromAgencyNumber(int agencyNumber) {
return Arrays.stream(values())
.filter(agency -> agency.agencyNumber == agencyNumber)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unsupported credit agency number: " + agencyNumber));
}
}
54 changes: 35 additions & 19 deletions src/main/java/com/augment/cbsa/service/CrecustService.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class CrecustService {
DateTimeFormatter.ofPattern("ddMMuuuu").withResolverStyle(ResolverStyle.STRICT);
private static final int CREDIT_AGENCY_COUNT = 5;
private static final int REVIEW_DATE_BOUND = 20;
private static final long CREDIT_AGENCY_TIMEOUT_SECONDS = 6;
private static final long CREDIT_AGENCY_REPLY_WINDOW_SECONDS = 3;
private static final List<String> VALID_TITLES = List.of(
"Professor", "Mr", "Mrs", "Miss", "Ms", "Dr", "Drs", "Lord", "Sir", "Lady", ""
);
Expand Down Expand Up @@ -151,37 +151,53 @@ private CreditDecision evaluateCredit(CrecustRequest request, LocalDate today) {
futures.add(creditAgencyService.requestCreditScore(request, agencyNumber));
}

// Single overall reply window across all agencies, mirroring the COBOL
// DELAY FOR SECONDS(3) + FETCH ANY NOSUSPEND flow. Wait for whichever
// agencies finish before the deadline and ignore the rest, so one slow
// agency cannot starve replies that already completed.
try {
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
.get(CREDIT_AGENCY_REPLY_WINDOW_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException ignored) {
// Some agencies did not reply within the overall window; fall through
// and harvest whichever did complete.
} catch (ExecutionException | CompletionException ignored) {
// Ignore individual credit-agency failures and average only successful replies.
} catch (InterruptedException exception) {
// Treat interruption as an immediate overall credit-check failure
// so we do not persist a customer based on partially collected
// scores while cancellation is being signaled.
Thread.currentThread().interrupt();
for (CompletableFuture<Optional<Integer>> future : futures) {
future.cancel(true);
}
return null;
}

int totalScore = 0;
int returnedScores = 0;
boolean interrupted = false;
for (CompletableFuture<Optional<Integer>> future : futures) {
if (interrupted) {
future.cancel(true);
if (future.isCompletedExceptionally() || future.isCancelled()) {
continue;
}
// cancel(true) returns false if the future already completed
// normally, in which case we still harvest its score; this avoids
// dropping replies that completed between isDone() and cancel().
if (!future.isDone() && future.cancel(true)) {
continue;
}
try {
Optional<Integer> maybeScore = future.get(CREDIT_AGENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS);
Optional<Integer> maybeScore = future.getNow(Optional.empty());
if (maybeScore.isPresent()) {
totalScore += maybeScore.get();
returnedScores++;
}
} catch (TimeoutException exception) {
// Bound the wait per agency so a hung credit-agency call cannot
// block the request indefinitely; treat as fail code G fodder.
future.cancel(true);
} catch (ExecutionException | CompletionException exception) {
// Ignore individual credit-agency failures and average only successful replies.
} catch (InterruptedException exception) {
// Treat interruption as an immediate overall credit-check failure
// so we do not persist a customer based on partially collected
// scores while cancellation is being signaled.
Thread.currentThread().interrupt();
future.cancel(true);
interrupted = true;
} catch (CompletionException ignored) {
// Individual agency failure; average only successful replies.
}
}

if (interrupted || returnedScores == 0) {
if (returnedScores == 0) {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.augment.cbsa.service;

import java.time.Duration;

@FunctionalInterface
public interface CreditAgencyDelayExecutor {

void delay(Duration duration) throws InterruptedException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.augment.cbsa.service;

import com.augment.cbsa.domain.CreditAgency;
import java.time.Duration;

@FunctionalInterface
public interface CreditAgencyDelayGenerator {

Duration nextDelay(CreditAgency agency);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.augment.cbsa.service;

import com.augment.cbsa.domain.CreditAgency;
import com.augment.cbsa.domain.CrecustRequest;

@FunctionalInterface
public interface CreditAgencyScoreGenerator {

int nextCreditScore(CreditAgency agency, CrecustRequest request);
}
38 changes: 32 additions & 6 deletions src/main/java/com/augment/cbsa/service/CreditAgencyService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.augment.cbsa.service;

import com.augment.cbsa.domain.CreditAgency;
import com.augment.cbsa.domain.CrecustRequest;
import com.augment.cbsa.error.CbsaAbendException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand All @@ -10,17 +12,41 @@
@Service
public class CreditAgencyService {

private final CreditAgencyDelayGenerator delayGenerator;
private final CreditAgencyDelayExecutor delayExecutor;
private final CreditAgencyScoreGenerator scoreGenerator;

public CreditAgencyService(
CreditAgencyDelayGenerator delayGenerator,
CreditAgencyDelayExecutor delayExecutor,
CreditAgencyScoreGenerator scoreGenerator
) {
this.delayGenerator = Objects.requireNonNull(delayGenerator, "delayGenerator must not be null");
this.delayExecutor = Objects.requireNonNull(delayExecutor, "delayExecutor must not be null");
this.scoreGenerator = Objects.requireNonNull(scoreGenerator, "scoreGenerator must not be null");
}

@Async("creditAgencyExecutor")
public CompletableFuture<Optional<Integer>> requestCreditScore(CrecustRequest request, int agencyNumber) {
Objects.requireNonNull(request, "request must not be null");
if (agencyNumber < 1) {
throw new IllegalArgumentException("agencyNumber must be positive");
CreditAgency agency = CreditAgency.fromAgencyNumber(agencyNumber);

try {
delayExecutor.delay(delayGenerator.nextDelay(agency));
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return CompletableFuture.failedFuture(new CbsaAbendException(
"PLOP",
"Credit agency processing was interrupted.",
exception
));
}

int score = scoreGenerator.nextCreditScore(agency, request);
if (score < 1 || score > 998) {
throw new IllegalArgumentException("credit agency score must be between 1 and 998");
}

int score = Math.floorMod(
Objects.hash(request.name().stripTrailing(), request.address().stripTrailing(), request.dateOfBirth(), agencyNumber),
900
) + 100;
return CompletableFuture.completedFuture(Optional.of(score));
}
}
91 changes: 91 additions & 0 deletions src/main/java/com/augment/cbsa/web/crdtagy/CrdtagyController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.augment.cbsa.web.crdtagy;

import com.augment.cbsa.domain.CrecustRequest;
import com.augment.cbsa.error.CbsaAbendException;
import com.augment.cbsa.service.CreditAgencyService;
import com.augment.cbsa.web.crecust.dto.CrecustCommareaResponseDto;
import com.augment.cbsa.web.crecust.dto.CrecustRequestDto;
import com.augment.cbsa.web.crecust.dto.CrecustResponseDto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
@RequestMapping("/api/v1/crdtagy")
public class CrdtagyController {

private static final long CREDIT_AGENCY_TIMEOUT_SECONDS = 5;

private final CreditAgencyService creditAgencyService;

public CrdtagyController(CreditAgencyService creditAgencyService) {
this.creditAgencyService = Objects.requireNonNull(creditAgencyService, "creditAgencyService must not be null");
}

@PostMapping("/{agencyNumber}")
public CrecustResponseDto process(
@PathVariable @Min(1) @Max(5) int agencyNumber,
@Valid @RequestBody CrecustRequestDto requestDto
) {
var commarea = requestDto.creCust();
int creditScore = awaitCreditScore(new CrecustRequest(
commarea.commName(),
commarea.commAddress(),
commarea.commDateOfBirth()
), agencyNumber);

return new CrecustResponseDto(new CrecustCommareaResponseDto(
defaultString(commarea.commEyecatcher()),
commarea.commKey(),
commarea.commName(),
commarea.commAddress(),
commarea.commDateOfBirth(),
creditScore,
defaultInt(commarea.commCsReviewDate()),
defaultString(commarea.commSuccess()),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On successful processing, CommSuccess / CommFailCode are currently echoed from the request (and defaulted), so callers can receive a credit score but still see a blank/incorrect success indicator. Consider populating these fields from the actual outcome (similar to other controllers) so the response consistently signals success/failure.

Severity: medium

🤖 Was this useful? React with 👍 or 👎

defaultString(commarea.commFailCode())
));
}

private int awaitCreditScore(CrecustRequest request, int agencyNumber) {
CompletableFuture<java.util.Optional<Integer>> future =
creditAgencyService.requestCreditScore(request, agencyNumber);
try {
return future.get(CREDIT_AGENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS).orElse(0);
} catch (TimeoutException exception) {
future.cancel(true);
throw new CbsaAbendException("PLOP", "Credit agency processing timed out.", exception);
} catch (ExecutionException | CompletionException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new IllegalStateException("Credit agency processing failed.", cause);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
future.cancel(true);
throw new CbsaAbendException("PLOP", "Credit agency processing was interrupted.", exception);
}
}

private String defaultString(String value) {
return value == null ? "" : value;
}

private int defaultInt(Integer value) {
return value == null ? 0 : value;
}
}
Loading
Loading