Skip to content

Commit 18bd00f

Browse files
authored
Merge pull request #490 from CodeForPhilly/issue/484-duplicate-check-name-fails-with-an-opaque-500-an
Handle duplicate check names without opaque errors
2 parents d7d9b0d + f02b5d0 commit 18bd00f

13 files changed

Lines changed: 357 additions & 4 deletions

File tree

‎.github/workflows/run-frontend-tests.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ jobs:
1717
- name: Checkout
1818
uses: actions/checkout@v4
1919

20+
- name: Load frontend ENV file from example
21+
run: cp builder-frontend/.env.example builder-frontend/.env
22+
2023
- name: Setup devbox
2124
uses: ./.github/actions/devbox-setup
2225

‎builder-api/src/main/java/org/acme/controller/EligibilityCheckResource.java‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.acme.model.dto.EligibilityCheck.CheckDmnRequest;
1616
import org.acme.model.dto.EligibilityCheck.CreateCheckRequest;
1717
import org.acme.model.dto.EligibilityCheck.EditCheckRequest;
18+
import org.acme.persistence.DocumentAlreadyExistsException;
1819
import org.acme.persistence.EligibilityCheckRepository;
1920
import org.acme.persistence.StorageService;
2021
import org.acme.service.CustomCheckDmnTemplate;
@@ -83,11 +84,20 @@ public Response createCustomCheck(@Context SecurityIdentity identity,
8384
request.parameterDefinitions(),
8485
userId
8586
);
87+
String checkId = eligibilityCheckRepository.getWorkingId(newCheck);
88+
Optional<EligibilityCheck> existingCheck = eligibilityCheckRepository
89+
.getWorkingCustomCheck(userId, checkId, true);
90+
if (existingCheck.isPresent()) {
91+
return duplicateCheckResponse(request, existingCheck.get().getIsArchived());
92+
}
93+
8694
String initialDmnModel = customCheckDmnTemplate.create(request.name(), request.description());
8795

88-
String checkId;
8996
try {
9097
checkId = eligibilityCheckRepository.saveNewWorkingCustomCheck(newCheck);
98+
} catch (DocumentAlreadyExistsException e) {
99+
Log.info("Check " + checkId + " was created concurrently");
100+
return duplicateCheckResponse(request, false);
91101
} catch (Exception e){
92102
Log.error("Could not save new check for user " + userId, e);
93103
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
@@ -121,6 +131,18 @@ public Response createCustomCheck(@Context SecurityIdentity identity,
121131
return Response.ok(newCheck, MediaType.APPLICATION_JSON).build();
122132
}
123133

134+
private Response duplicateCheckResponse(CreateCheckRequest request, boolean archived) {
135+
String message = archived
136+
? "A check named \"" + request.name() + "\" in module \"" + request.module()
137+
+ "\" is archived. Restore it or choose a different name."
138+
: "You already have a check named \"" + request.name() + "\" in module \""
139+
+ request.module() + "\".";
140+
return Response.status(Response.Status.CONFLICT)
141+
.type(MediaType.APPLICATION_JSON)
142+
.entity(Map.of("error", message))
143+
.build();
144+
}
145+
124146
// ========== Single Resource Endpoints ==========
125147

126148
@GET
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package org.acme.persistence;
2+
3+
public class DocumentAlreadyExistsException extends Exception {
4+
5+
public DocumentAlreadyExistsException(String documentId, Throwable cause) {
6+
super("Document already exists: " + documentId, cause);
7+
}
8+
}

‎builder-api/src/main/java/org/acme/persistence/EligibilityCheckRepository.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ public interface EligibilityCheckRepository {
2222

2323
Optional<EligibilityCheck> getPublishedCustomCheck(String userId, String checkId);
2424

25+
String getWorkingId(EligibilityCheck check);
26+
2527
String saveNewWorkingCustomCheck(EligibilityCheck check) throws Exception;
2628

2729
String saveNewPublishedCustomCheck(EligibilityCheck check) throws Exception;

‎builder-api/src/main/java/org/acme/persistence/FirestoreUtils.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.acme.persistence;
22

33
import com.google.api.core.ApiFuture;
4+
import com.google.api.gax.rpc.ApiException;
5+
import com.google.api.gax.rpc.StatusCode;
46
import com.google.cloud.firestore.*;
57
import com.google.firebase.cloud.FirestoreClient;
68
import io.quarkus.logging.Log;
@@ -187,6 +189,10 @@ public static String persistDocumentWithId(String collectionPath, String documen
187189
throw new Exception("Thread interrupted while saving to Firestore", e);
188190
} catch (ExecutionException e) {
189191
Log.error(e);
192+
if (e.getCause() instanceof ApiException apiException
193+
&& apiException.getStatusCode().getCode() == StatusCode.Code.ALREADY_EXISTS) {
194+
throw new DocumentAlreadyExistsException(documentId, e);
195+
}
190196
throw new Exception("Failed to write document to Firestore", e);
191197
}
192198
}

‎builder-api/src/main/java/org/acme/persistence/impl/EligibilityCheckRepositoryImpl.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ public void updatePublishedCustomCheck(EligibilityCheck check) throws Exception{
188188
FirestoreUtils.updateDocument(CollectionNames.PUBLISHED_CUSTOM_CHECK_COLLECTION, data, check.getId());
189189
}
190190

191+
@Override
191192
public String getWorkingId(EligibilityCheck check) {
192193
return CheckStatus.WORKING.getCode() + "-" + check.getOwnerId() + "-" + check.getModule() + "-" + check.getName();
193194
}

‎builder-api/src/test/java/org/acme/controller/EligibilityCheckResourceTest.java‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import org.acme.model.domain.EligibilityCheck;
77
import org.acme.model.dto.EligibilityCheck.CreateCheckRequest;
88
import org.acme.persistence.EligibilityCheckRepository;
9+
import org.acme.persistence.DocumentAlreadyExistsException;
910
import org.acme.persistence.StorageService;
1011
import org.acme.service.CustomCheckDmnTemplate;
1112
import org.acme.service.DmnService;
@@ -61,6 +62,10 @@ void setUp() throws Exception {
6162
when(dmnService.extractInputSchema(anyString(), any(), anyString()))
6263
.thenReturn(new ObjectMapper().createObjectNode());
6364
when(repository.saveNewPublishedCustomCheck(any())).thenReturn("published-check-1");
65+
when(repository.getWorkingId(any())).thenAnswer(invocation -> {
66+
EligibilityCheck check = invocation.getArgument(0);
67+
return "W-" + check.getOwnerId() + "-" + check.getModule() + "-" + check.getName();
68+
});
6469
}
6570

6671
@Test
@@ -118,6 +123,66 @@ void createCustomCheckRemovesTheCheckWhenItsDmnCannotBeStored() throws Exception
118123
verify(repository).deleteWorkingCustomCheck(checkId);
119124
}
120125

126+
@Test
127+
void createCustomCheckRejectsAnExistingActiveCheck() throws Exception {
128+
CreateCheckRequest request = createCheckRequest();
129+
String checkId = "W-owner-1-income-incomeCheck";
130+
EligibilityCheck existing = new EligibilityCheck(
131+
request.name(), request.module(), request.description(), List.of(), USER_ID);
132+
when(repository.getWorkingCustomCheck(USER_ID, checkId, true)).thenReturn(Optional.of(existing));
133+
134+
Response response = resource.createCustomCheck(identity, request);
135+
136+
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());
137+
assertEquals(
138+
"You already have a check named \"incomeCheck\" in module \"income\".",
139+
((java.util.Map<?, ?>) response.getEntity()).get("error"));
140+
verify(repository, never()).saveNewWorkingCustomCheck(any());
141+
verify(storageService, never()).writeStringToStorage(anyString(), anyString(), anyString());
142+
}
143+
144+
@Test
145+
void createCustomCheckExplainsAnArchivedCollision() throws Exception {
146+
CreateCheckRequest request = createCheckRequest();
147+
String checkId = "W-owner-1-income-incomeCheck";
148+
EligibilityCheck existing = new EligibilityCheck(
149+
request.name(), request.module(), request.description(), List.of(), USER_ID);
150+
existing.setIsArchived(true);
151+
when(repository.getWorkingCustomCheck(USER_ID, checkId, true)).thenReturn(Optional.of(existing));
152+
153+
Response response = resource.createCustomCheck(identity, request);
154+
155+
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());
156+
assertEquals(
157+
"A check named \"incomeCheck\" in module \"income\" is archived. Restore it or choose a different name.",
158+
((java.util.Map<?, ?>) response.getEntity()).get("error"));
159+
verify(repository, never()).saveNewWorkingCustomCheck(any());
160+
}
161+
162+
@Test
163+
void createCustomCheckMapsAConcurrentCollisionToConflict() throws Exception {
164+
CreateCheckRequest request = createCheckRequest();
165+
String checkId = "W-owner-1-income-incomeCheck";
166+
when(repository.saveNewWorkingCustomCheck(any()))
167+
.thenThrow(new DocumentAlreadyExistsException(checkId, new RuntimeException()));
168+
169+
Response response = resource.createCustomCheck(identity, request);
170+
171+
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());
172+
assertEquals(
173+
"You already have a check named \"incomeCheck\" in module \"income\".",
174+
((java.util.Map<?, ?>) response.getEntity()).get("error"));
175+
verify(storageService, never()).writeStringToStorage(anyString(), anyString(), anyString());
176+
}
177+
178+
private CreateCheckRequest createCheckRequest() {
179+
return new CreateCheckRequest(
180+
"incomeCheck",
181+
"income",
182+
"Checks the applicant's income",
183+
List.of());
184+
}
185+
121186
@Test
122187
void firstPublishKeepsInitialVersion() throws Exception {
123188
when(repository.getPublishedCheckVersions(workingCheck)).thenReturn(List.of());
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
vi.mock("@/api/auth", () => ({
4+
authGet: vi.fn(),
5+
authPatch: vi.fn(),
6+
authPost: vi.fn(),
7+
authPut: vi.fn(),
8+
}));
9+
10+
import { authPost } from "@/api/auth";
11+
import { addCheck, ApiError } from "./check";
12+
13+
const request = {
14+
name: "incomeCheck",
15+
module: "income",
16+
description: "Checks income",
17+
parameterDefinitions: [],
18+
};
19+
20+
describe("addCheck", () => {
21+
beforeEach(() => vi.clearAllMocks());
22+
23+
it("reports the API error message when check creation fails", async () => {
24+
vi.mocked(authPost).mockResolvedValue(
25+
new Response(
26+
JSON.stringify({
27+
error:
28+
'You already have a check named "incomeCheck" in module "income".',
29+
}),
30+
{ status: 409, headers: { "Content-Type": "application/json" } },
31+
),
32+
);
33+
34+
await expect(addCheck(request)).rejects.toThrow(
35+
'You already have a check named "incomeCheck" in module "income".',
36+
);
37+
});
38+
39+
it("carries the response status so callers can tell failures apart", async () => {
40+
vi.mocked(authPost).mockResolvedValue(
41+
new Response(JSON.stringify({ error: "Could not save Check" }), {
42+
status: 500,
43+
headers: { "Content-Type": "application/json" },
44+
}),
45+
);
46+
47+
await expect(addCheck(request)).rejects.toMatchObject({
48+
status: 500,
49+
});
50+
});
51+
52+
it("falls back to the status when the error response is not JSON", async () => {
53+
vi.mocked(authPost).mockResolvedValue(
54+
new Response("unavailable", { status: 503 }),
55+
);
56+
57+
await expect(addCheck(request)).rejects.toThrow(
58+
"Post failed with status: 503",
59+
);
60+
});
61+
62+
it("rejects with an ApiError", async () => {
63+
vi.mocked(authPost).mockResolvedValue(
64+
new Response("unavailable", { status: 503 }),
65+
);
66+
67+
await expect(addCheck(request)).rejects.toBeInstanceOf(ApiError);
68+
});
69+
});

‎builder-frontend/src/api/check.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ import type {
1010

1111
const apiUrl = env.apiUrl;
1212

13+
/* Carries the response status so callers can tell a rejected request apart from a failed one. */
14+
export class ApiError extends Error {
15+
readonly status: number;
16+
17+
constructor(message: string, status: number) {
18+
super(message);
19+
this.name = "ApiError";
20+
this.status = status;
21+
}
22+
}
23+
1324
export const fetchPublicChecks = async (): Promise<EligibilityCheck[]> => {
1425
const url = apiUrl + "/library-checks";
1526
try {
@@ -63,7 +74,14 @@ export const addCheck = async (
6374
});
6475

6576
if (!response.ok) {
66-
throw new Error(`Post failed with status: ${response.status}`);
77+
let message = `Post failed with status: ${response.status}`;
78+
try {
79+
const body = await response.json();
80+
if (typeof body.error === "string") message = body.error;
81+
} catch {
82+
// Keep the status-based fallback when the server does not return JSON.
83+
}
84+
throw new ApiError(message, response.status);
6785
}
6886
const data = await response.json();
6987
return data;
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { createRoot } from "solid-js";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
vi.mock("@/api/check", () => ({
5+
addCheck: vi.fn(),
6+
archiveCheck: vi.fn(),
7+
fetchUserDefinedChecks: vi.fn().mockResolvedValue([]),
8+
}));
9+
10+
import { addCheck } from "@/api/check";
11+
import eligibilityCheckResource from "./eligibilityCheckResource";
12+
13+
describe("eligibilityCheckResource", () => {
14+
beforeEach(() => vi.clearAllMocks());
15+
16+
it("propagates create failures to the modal", async () => {
17+
const failure = new Error("That check name is already in use.");
18+
vi.mocked(addCheck).mockRejectedValue(failure);
19+
20+
await new Promise<void>((resolve, reject) => {
21+
createRoot((dispose) => {
22+
const resource = eligibilityCheckResource();
23+
resource.actions
24+
.addNewCheck({
25+
name: "incomeCheck",
26+
module: "income",
27+
description: "Checks income",
28+
parameterDefinitions: [],
29+
})
30+
.then(() => reject(new Error("Expected check creation to fail")))
31+
.catch((error) => {
32+
try {
33+
expect(error).toBe(failure);
34+
expect(resource.actionInProgress()).toBe(false);
35+
resolve();
36+
} catch (assertionError) {
37+
reject(assertionError);
38+
} finally {
39+
dispose();
40+
}
41+
});
42+
});
43+
});
44+
});
45+
});

0 commit comments

Comments
 (0)