Skip to content

Commit edf40d5

Browse files
authored
refactor: unify solution retrieval logic from database and client
### What was done - Updated endpoint URLs and consolidated result endpoints into getResults. - Refactored result retrieval by replacing individual queries with a unified query in getResults. - Adjusted client calls to reflect the new unified /results/{applicationId} endpoint. - Modified integration to parse the unified result data for solution and graph values.
2 parents 1f39171 + be4d7c0 commit edf40d5

4 files changed

Lines changed: 42 additions & 151 deletions

File tree

solver-bot/src/main/python/shell.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@
1010
set_parameters,
1111
set_user_settings,
1212
get_user_settings,
13-
get_x_values,
14-
get_y_values,
15-
get_solution,
1613
get_recent_applications,
14+
get_results,
1715
wait_for_application_completion)
1816
from equation.equation_parser import format_equation
1917
from equation.equation_validator import (
@@ -450,6 +448,7 @@ async def solve_history_details(update: Update, context: ContextTypes.DEFAULT_TY
450448

451449
application = recent_applications[application_index]
452450
application_id = application.get('id')
451+
results = await get_results(application_id)
453452

454453
try:
455454
parameters = json.loads(application.get("parameters", "{}"))
@@ -462,9 +461,10 @@ async def solve_history_details(update: Update, context: ContextTypes.DEFAULT_TY
462461
reach_point = parameters.get("reachPoint", "")
463462
step_size = parameters.get("stepSize", "")
464463

465-
x_values = await get_x_values(application_id)
466-
y_values = await get_y_values(application_id)
467-
solution = await get_solution(application_id)
464+
data = json.loads(results[0].get("data", "{}"))
465+
x_values = data.get("xvalues", [])
466+
y_values = data.get("yvalues", [])
467+
solution = data.get("solution", "")
468468

469469
plot_graph = plot_solution(x_values, y_values, order)
470470

@@ -839,10 +839,13 @@ async def solution(update: Update, context: ContextTypes.DEFAULT_TYPE):
839839
)
840840
return MENU
841841

842+
results = await get_results(application_id)
843+
842844
try:
843-
result = await get_solution(application_id)
844-
x_values = await get_x_values(application_id)
845-
y_values = await get_y_values(application_id)
845+
data = json.loads(results[0].get("data", "{}"))
846+
x_values = data.get("xvalues", [])
847+
y_values = data.get("yvalues", [])
848+
solution = data.get("solution", "")
846849
except Exception:
847850
logger.error("Error while getting solution for application %s", application_id)
848851
await save_user_settings(context)
@@ -853,7 +856,7 @@ async def solution(update: Update, context: ContextTypes.DEFAULT_TYPE):
853856
)
854857
return MENU
855858

856-
if result is None:
859+
if solution is None:
857860
logger.info("User %s used unsupported symbols", user.id)
858861
await save_user_settings(context)
859862
await processing_message.edit_text(
@@ -870,7 +873,7 @@ async def solution(update: Update, context: ContextTypes.DEFAULT_TYPE):
870873
)
871874

872875
print_result = print_solution(
873-
result,
876+
solution,
874877
context.user_data['order'],
875878
context.user_data['rounding']
876879
)

solver-bot/src/main/python/spring_client.py

Lines changed: 5 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ async def get_recent_applications(user_id):
9595
timeout = ClientTimeout(total=REQUEST_TIMEOUT)
9696
async with ClientSession(timeout=timeout) as session:
9797
async with session.get(
98-
f"{os.getenv("CLIENT_API_URL")}/applications/list/{user_id}"
98+
f"{os.getenv("CLIENT_API_URL")}/applications/{user_id}"
9999
) as response:
100100
if response.status == 500:
101101
return []
@@ -132,58 +132,19 @@ async def get_recent_applications(user_id):
132132
return []
133133

134134

135-
async def get_solution(application_id):
135+
async def get_results(application_id):
136136
timeout = ClientTimeout(total=REQUEST_TIMEOUT)
137137
async with ClientSession(timeout=timeout) as session:
138138
async with session.get(
139-
f"{os.getenv("CLIENT_API_URL")}/results/{application_id}/solution"
139+
f"{os.getenv("CLIENT_API_URL")}/results/{application_id}"
140140
) as response:
141-
if response.status == 500:
142-
return []
143-
144-
response.raise_for_status()
145-
text = await response.text()
146-
try:
147-
data = json.loads(text)
148-
except json.JSONDecodeError:
149-
raise ValueError(f"Failed to parse solution data: {text}")
150-
return np.array(data)
151-
152-
153-
async def get_x_values(application_id):
154-
timeout = ClientTimeout(total=REQUEST_TIMEOUT)
155-
async with ClientSession(timeout=timeout) as session:
156-
async with session.get(
157-
f"{os.getenv("CLIENT_API_URL")}/results/{application_id}/xvalues"
158-
) as response:
159-
if response.status == 500:
160-
return []
161-
162141
response.raise_for_status()
163142
text = await response.text()
164143
try:
165144
data = json.loads(text)
166145
except json.JSONDecodeError:
167-
raise ValueError(f"Failed to parse x-values data: {text}")
168-
return np.array(data)
169-
170-
171-
async def get_y_values(application_id):
172-
timeout = ClientTimeout(total=REQUEST_TIMEOUT)
173-
async with ClientSession(timeout=timeout) as session:
174-
async with session.get(
175-
f"{os.getenv("CLIENT_API_URL")}/results/{application_id}/yvalues"
176-
) as response:
177-
if response.status == 500:
178-
return []
179-
180-
response.raise_for_status()
181-
text = await response.text()
182-
try:
183-
data = json.loads(text)
184-
except json.JSONDecodeError:
185-
raise ValueError(f"Failed to parse y-values data: {text}")
186-
return np.array(data)
146+
return text
147+
return data
187148

188149

189150
async def get_application_status(application_id):

solver-common/src/main/java/com/solver/DBService.java

Lines changed: 12 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.solver;
22

3-
import com.fasterxml.jackson.core.JsonProcessingException;
4-
import com.fasterxml.jackson.databind.ObjectMapper;
53
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
75
import org.springframework.dao.DataAccessException;
@@ -12,7 +10,6 @@
1210
import org.springframework.stereotype.Service;
1311
import org.springframework.transaction.annotation.Transactional;
1412

15-
import java.util.ArrayList;
1613
import java.util.concurrent.CompletableFuture;
1714
import java.util.HashMap;
1815
import java.util.List;
@@ -147,80 +144,25 @@ public CompletableFuture<List<Map<String, Object>>> getApplications(Integer user
147144

148145
@Async
149146
@Transactional
150-
public CompletableFuture<Optional<List<Double>>> getXValues(int applicationId) {
151-
logger.debug("Fetching x values for applicationId: {}", applicationId);
147+
public CompletableFuture<List<Map<String, Object>>> getResults(Integer applicationId) {
148+
logger.debug("Fetching results for applicationId: {}", applicationId);
152149
return CompletableFuture.supplyAsync(() -> {
153150
String query = """
154-
SELECT jsonb_array_elements_text(data->'xvalues')::double precision AS x_value
151+
SELECT id, data, created_at
155152
FROM results
156153
WHERE application_id = ?
157154
""";
158155
try {
159-
List<Double> xValues = jdbcTemplate.queryForList(query, Double.class, applicationId);
160-
return xValues.isEmpty() ? Optional.empty() : Optional.of(xValues);
161-
} catch (DataAccessException e) {
162-
logger.error("Database error while fetching x values for applicationId: {}", applicationId, e);
163-
throw new SolverException("Failed to fetch x values", e);
164-
}
165-
});
166-
}
167-
168-
@Async
169-
@Transactional
170-
public CompletableFuture<Optional<List<double[]>>> getYValues(int applicationId) {
171-
logger.debug("Fetching y values for applicationId: {}", applicationId);
172-
return CompletableFuture.supplyAsync(() -> {
173-
String query = """
174-
SELECT jsonb_array_elements(data->'yvalues')::jsonb AS y_value
175-
FROM results
176-
WHERE application_id = ?
177-
""";
178-
try {
179-
List<String> yValuesJson = jdbcTemplate.queryForList(query, String.class, applicationId);
180-
if (yValuesJson.isEmpty()) {
181-
return Optional.empty();
182-
}
183-
184-
ObjectMapper objectMapper = new ObjectMapper();
185-
List<double[]> yValues = new ArrayList<>();
186-
for (String json : yValuesJson) {
187-
yValues.add(objectMapper.readValue(json, double[].class));
188-
}
189-
return Optional.of(yValues);
190-
} catch (DataAccessException e) {
191-
logger.error("Database error while fetching y values for applicationId: {}", applicationId, e);
192-
throw new SolverException("Failed to fetch y values", e);
193-
} catch (JsonProcessingException e) {
194-
logger.error("JSON processing error while parsing y values for applicationId: {}", applicationId, e);
195-
throw new SolverException("Failed to parse y values", e);
196-
}
197-
});
198-
}
199-
200-
@Async
201-
@Transactional
202-
public CompletableFuture<Optional<double[]>> getSolution(int applicationId) {
203-
logger.debug("Fetching solution for applicationId: {}", applicationId);
204-
return CompletableFuture.supplyAsync(() -> {
205-
String query = """
206-
SELECT data->>'solution' AS solution
207-
FROM results
208-
WHERE application_id = ?
209-
""";
210-
try {
211-
List<String> solutions = jdbcTemplate.queryForList(query, String.class, applicationId);
212-
if (solutions.isEmpty()) {
213-
return Optional.empty();
214-
}
215-
216-
ObjectMapper objectMapper = new ObjectMapper();
217-
return Optional.of(objectMapper.readValue(solutions.getFirst(), double[].class));
156+
return jdbcTemplate.query(query, (rs, rowNum) -> {
157+
Map<String, Object> result = new HashMap<>();
158+
result.put("id", rs.getInt("id"));
159+
result.put("data", rs.getString("data"));
160+
result.put("created_at", rs.getString("created_at"));
161+
return result;
162+
}, applicationId);
218163
} catch (DataAccessException e) {
219-
logger.error("Database error while fetching solution for applicationId: {}", applicationId, e);
220-
throw new SolverException("Failed to fetch solution", e);
221-
} catch (JsonProcessingException e) {
222-
logger.error("JSON processing error while parsing solution for applicationId: {}", applicationId, e);
223-
throw new SolverException("Failed to parse solution", e);
164+
logger.error("Database error while fetching results for applicationId: {}", applicationId, e);
165+
throw new SolverException("Failed to fetch results", e);
224166
}
225167
});
226168
}

solver-common/src/main/java/com/solver/SolverController.java

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public CompletableFuture<ResponseEntity<String>> getApplicationStatus(@PathVaria
110110
.orElseThrow(() -> new SolverException("Application status not found for applicationId: " + applicationId)));
111111
}
112112

113-
@GetMapping("/applications/list/{userId}")
113+
@GetMapping("/applications/{userId}")
114114
public CompletableFuture<ResponseEntity<List<Map<String, Object>>>> getApplications(@PathVariable("userId") Integer userId) {
115115
logger.debug("Getting applications list for userId: {}", userId);
116116
return dbService.getApplications(userId)
@@ -122,30 +122,15 @@ public CompletableFuture<ResponseEntity<List<Map<String, Object>>>> getApplicati
122122
});
123123
}
124124

125-
@GetMapping("/results/{applicationId}/solution")
126-
public CompletableFuture<ResponseEntity<double[]>> getSolution(@PathVariable("applicationId") int applicationId) {
127-
logger.debug("Getting solution for applicationId: {}", applicationId);
128-
return dbService.getSolution(applicationId)
129-
.thenApply(optionalSolution -> optionalSolution
130-
.map(ResponseEntity::ok)
131-
.orElseThrow(() -> new SolverException("Solution not found for applicationId: " + applicationId)));
132-
}
133-
134-
@GetMapping("/results/{applicationId}/xvalues")
135-
public CompletableFuture<ResponseEntity<List<Double>>> getXValues(@PathVariable("applicationId") int applicationId) {
136-
logger.debug("Getting x values for applicationId: {}", applicationId);
137-
return dbService.getXValues(applicationId)
138-
.thenApply(optionalXValues -> optionalXValues
139-
.map(ResponseEntity::ok)
140-
.orElseThrow(() -> new SolverException("xValues not found for applicationId: " + applicationId)));
141-
}
142-
143-
@GetMapping("/results/{applicationId}/yvalues")
144-
public CompletableFuture<ResponseEntity<List<double[]>>> getYValues(@PathVariable("applicationId") int applicationId) {
145-
logger.debug("Getting y values for applicationId: {}", applicationId);
146-
return dbService.getYValues(applicationId)
147-
.thenApply(optionalYValues -> optionalYValues
148-
.map(ResponseEntity::ok)
149-
.orElseThrow(() -> new SolverException("yValues not found for applicationId: " + applicationId)));
125+
@GetMapping("/results/{applicationId}")
126+
public CompletableFuture<ResponseEntity<List<Map<String, Object>>>> getResults(@PathVariable("applicationId") Integer applicationId) {
127+
logger.debug("Getting results for applicationId: {}", applicationId);
128+
return dbService.getResults(applicationId)
129+
.thenApply(results -> {
130+
if (results.isEmpty()) {
131+
throw new SolverException("Results not found for applicationId: " + applicationId);
132+
}
133+
return ResponseEntity.ok(results);
134+
});
150135
}
151136
}

0 commit comments

Comments
 (0)