Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(tagging): deduplicate tag-dispatch logic across tag controllers (#3594) (#3619)
Vũ Thế Huy7981e23dcd60
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AbstractTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/AbstractTagsController.javanew file mode 100644index 0000000000..10db05b940--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/AbstractTagsController.java@@ -0,0 +1,73 @@+package io.github.hectorvent.floci.core.common;++import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.DELETE;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.PUT;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;++/**+ * Base REST controller for tag endpoints mounted at {@code /{arn: .+}}.+ *+ * <p>Shared between {@link SharedTagsController} (mounted at {@code /tags}) and+ * {@link V1TagsController} (mounted at {@code /v1/tags}).+ */+@Produces(MediaType.APPLICATION_JSON)+public abstract class AbstractTagsController {++ private final TagDispatcher dispatcher;++ protected AbstractTagsController(TagDispatcher dispatcher) {+ this.dispatcher = dispatcher;+ }++ protected TagDispatcher dispatcher() {+ return dispatcher;+ }++ @GET+ @Path("/{arn: .+}")+ public Response listTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {+ return dispatcher.listTagsForArn(headers, arn);+ }++ @POST+ @Path("/{arn: .+}")+ @Consumes(MediaType.APPLICATION_JSON)+ public Response tagResourcePost(@Context HttpHeaders headers,+ @PathParam("arn") String arn,+ String body) {+ TagHandler handler = dispatcher.resolveHandler(arn);+ return dispatcher.tagResourcePost(headers, arn, body,+ Response.status(handler.tagResourceSuccessStatus()).build());+ }++ @PUT+ @Path("/{arn: .+}")+ @Consumes(MediaType.APPLICATION_JSON)+ public Response tagResourcePut(@Context HttpHeaders headers,+ @PathParam("arn") String arn,+ String body) {+ TagHandler handler = dispatcher.resolveHandler(arn);+ return dispatcher.tagResourcePut(headers, arn, body,+ Response.status(handler.tagResourceSuccessStatus()).build());+ }++ @DELETE+ @Path("/{arn: .+}")+ public Response untagResource(@Context HttpHeaders headers,+ @Context UriInfo uriInfo,+ @PathParam("arn") String arn) {+ TagHandler handler = dispatcher.resolveHandler(arn);+ return dispatcher.untagResourceForArn(headers, uriInfo, arn,+ Response.status(handler.untagResourceSuccessStatus()).build(), handler);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.javaindex 41b359bd89..e7e644e7d5 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java@@ -7,9 +7,7 @@ import jakarta.ws.rs.Consumes;import jakarta.ws.rs.DELETE;import jakarta.ws.rs.GET;import jakarta.ws.rs.POST;-import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;-import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;import jakarta.ws.rs.QueryParam;import jakarta.ws.rs.core.Context;@@ -34,75 +32,35 @@ import jakarta.ws.rs.core.UriInfo;*/@Path("/tags")@Produces(MediaType.APPLICATION_JSON)-public class SharedTagsController {-- private final TagDispatcher dispatcher;+public class SharedTagsController extends AbstractTagsController {@Injectpublic SharedTagsController(Instance<TagHandler> handlers,RegionResolver regionResolver,ObjectMapper objectMapper) {- this.dispatcher = new TagDispatcher(handlers, regionResolver, objectMapper);+ super(new TagDispatcher(handlers, regionResolver, objectMapper));}@GETpublic Response listTagsByQuery(@Context HttpHeaders headers,@QueryParam("resourceArn") String arn) {- return dispatcher.listTagsForArn(headers, arn);- }-- @GET- @Path("/{arn: .+}")- public Response listTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {- return dispatcher.listTagsForArn(headers, arn);+ return dispatcher().listTagsForArn(headers, arn);}@POST@Consumes(MediaType.APPLICATION_JSON)public Response tagResourceByBody(@Context HttpHeaders headers, String body) {- String arn = dispatcher.readResourceArn(body);- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.doTagResource(headers, handler, arn, body,- Response.ok(dispatcher.emptyObject()).build());- }-- @POST- @Path("/{arn: .+}")- @Consumes(MediaType.APPLICATION_JSON)- public Response tagResourcePost(@Context HttpHeaders headers,- @PathParam("arn") String arn,- String body) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.tagResourcePost(headers, arn, body,- Response.status(handler.tagResourceSuccessStatus()).build());- }-- @PUT- @Path("/{arn: .+}")- @Consumes(MediaType.APPLICATION_JSON)- public Response tagResourcePut(@Context HttpHeaders headers,- @PathParam("arn") String arn,- String body) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.tagResourcePut(headers, arn, body,- Response.status(handler.tagResourceSuccessStatus()).build());+ String arn = dispatcher().readResourceArn(body);+ TagHandler handler = dispatcher().resolveHandler(arn);+ return dispatcher().doTagResource(headers, handler, arn, body,+ Response.ok(dispatcher().emptyObject()).build());}@DELETEpublic Response untagResourceByQuery(@Context HttpHeaders headers,@Context UriInfo uriInfo,@QueryParam("resourceArn") String arn) {- return dispatcher.untagResourceForArn(headers, uriInfo, arn,- Response.ok(dispatcher.emptyObject()).build());- }-- @DELETE- @Path("/{arn: .+}")- public Response untagResource(@Context HttpHeaders headers,- @Context UriInfo uriInfo,- @PathParam("arn") String arn) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.untagResourceForArn(headers, uriInfo, arn,- Response.status(handler.untagResourceSuccessStatus()).build(), handler);+ return dispatcher().untagResourceForArn(headers, uriInfo, arn,+ Response.ok(dispatcher().emptyObject()).build());}}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/V1TagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/V1TagsController.javaindex b444d7a465..d5a06d6f13 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/V1TagsController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/V1TagsController.java@@ -3,19 +3,9 @@ package io.github.hectorvent.floci.core.common;import com.fasterxml.jackson.databind.ObjectMapper;import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;-import jakarta.ws.rs.Consumes;-import jakarta.ws.rs.DELETE;-import jakarta.ws.rs.GET;-import jakarta.ws.rs.POST;-import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;-import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;-import jakarta.ws.rs.core.Context;-import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.MediaType;-import jakarta.ws.rs.core.Response;-import jakarta.ws.rs.core.UriInfo;/*** Dispatcher for the AWS services that put their tag endpoints on {@code /v1/tags/{resourceArn}}@@ -28,52 +18,12 @@ import jakarta.ws.rs.core.UriInfo;*/@Path("/v1/tags")@Produces(MediaType.APPLICATION_JSON)-public class V1TagsController {-- private final TagDispatcher dispatcher;+public class V1TagsController extends AbstractTagsController {@Injectpublic V1TagsController(@V1Tags Instance<TagHandler> handlers,RegionResolver regionResolver,ObjectMapper objectMapper) {- this.dispatcher = new TagDispatcher(handlers, regionResolver, objectMapper);- }-- @GET- @Path("/{arn: .+}")- public Response listTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {- return dispatcher.listTagsForArn(headers, arn);- }-- @POST- @Path("/{arn: .+}")- @Consumes(MediaType.APPLICATION_JSON)- public Response tagResourcePost(@Context HttpHeaders headers,- @PathParam("arn") String arn,- String body) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.tagResourcePost(headers, arn, body,- Response.status(handler.tagResourceSuccessStatus()).build());- }-- @PUT- @Path("/{arn: .+}")- @Consumes(MediaType.APPLICATION_JSON)- public Response tagResourcePut(@Context HttpHeaders headers,- @PathParam("arn") String arn,- String body) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.tagResourcePut(headers, arn, body,- Response.status(handler.tagResourceSuccessStatus()).build());- }-- @DELETE- @Path("/{arn: .+}")- public Response untagResource(@Context HttpHeaders headers,- @Context UriInfo uriInfo,- @PathParam("arn") String arn) {- TagHandler handler = dispatcher.resolveHandler(arn);- return dispatcher.untagResourceForArn(headers, uriInfo, arn,- Response.status(handler.untagResourceSuccessStatus()).build(), handler);+ super(new TagDispatcher(handlers, regionResolver, objectMapper));}}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AbstractTagsControllerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AbstractTagsControllerTest.javanew file mode 100644index 0000000000..075b4e80e8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/AbstractTagsControllerTest.java@@ -0,0 +1,97 @@+package io.github.hectorvent.floci.core.common;++import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class AbstractTagsControllerTest {++ private TagDispatcher dispatcher;+ private TagHandler handler;+ private AbstractTagsController controller;++ private static class TestTagsController extends AbstractTagsController {+ TestTagsController(TagDispatcher dispatcher) {+ super(dispatcher);+ }+ }++ @BeforeEach+ void setUp() {+ dispatcher = mock(TagDispatcher.class);+ handler = mock(TagHandler.class);+ controller = new TestTagsController(dispatcher);+ }++ @Test+ void listTagsDelegatesToDispatcher() {+ HttpHeaders headers = mock(HttpHeaders.class);+ String arn = "arn:aws:apigateway:us-east-1::/restapis/123";+ Response expected = Response.ok().build();+ when(dispatcher.listTagsForArn(headers, arn)).thenReturn(expected);++ Response actual = controller.listTags(headers, arn);++ assertEquals(expected, actual);+ verify(dispatcher).listTagsForArn(headers, arn);+ }++ @Test+ void tagResourcePostDispatchesWithHandlerSuccessStatus() {+ HttpHeaders headers = mock(HttpHeaders.class);+ String arn = "arn:aws:kafka:us-east-1:000000000000:cluster/test/id";+ String body = "{\"tags\":{\"env\":\"test\"}}";+ when(dispatcher.resolveHandler(arn)).thenReturn(handler);+ when(handler.tagResourceSuccessStatus()).thenReturn(204);+ Response expected = Response.noContent().build();+ when(dispatcher.tagResourcePost(eq(headers), eq(arn), eq(body), any(Response.class))).thenReturn(expected);++ Response actual = controller.tagResourcePost(headers, arn, body);++ assertEquals(expected, actual);+ verify(dispatcher).tagResourcePost(eq(headers), eq(arn), eq(body), any(Response.class));+ }++ @Test+ void tagResourcePutDispatchesWithHandlerSuccessStatus() {+ HttpHeaders headers = mock(HttpHeaders.class);+ String arn = "arn:aws:apigateway:us-east-1::/restapis/123";+ String body = "{\"tags\":{\"env\":\"test\"}}";+ when(dispatcher.resolveHandler(arn)).thenReturn(handler);+ when(handler.tagResourceSuccessStatus()).thenReturn(200);+ Response expected = Response.ok().build();+ when(dispatcher.tagResourcePut(eq(headers), eq(arn), eq(body), any(Response.class))).thenReturn(expected);++ Response actual = controller.tagResourcePut(headers, arn, body);++ assertEquals(expected, actual);+ verify(dispatcher).tagResourcePut(eq(headers), eq(arn), eq(body), any(Response.class));+ }++ @Test+ void untagResourceDispatchesWithHandlerSuccessStatus() {+ HttpHeaders headers = mock(HttpHeaders.class);+ UriInfo uriInfo = mock(UriInfo.class);+ String arn = "arn:aws:apigateway:us-east-1::/restapis/123";+ when(dispatcher.resolveHandler(arn)).thenReturn(handler);+ when(handler.untagResourceSuccessStatus()).thenReturn(204);+ Response expected = Response.noContent().build();+ when(dispatcher.untagResourceForArn(eq(headers), eq(uriInfo), eq(arn), any(Response.class), eq(handler)))+ .thenReturn(expected);++ Response actual = controller.untagResource(headers, uriInfo, arn);++ assertEquals(expected, actual);+ verify(dispatcher).untagResourceForArn(eq(headers), eq(uriInfo), eq(arn), any(Response.class), eq(handler));+ }+}diff --git a/tools/docs/regen_action_docs.py b/tools/docs/regen_action_docs.pyindex 055022eee4..37f269be4c 100644--- a/tools/docs/regen_action_docs.py+++ b/tools/docs/regen_action_docs.py@@ -90,13 +90,10 @@ def extract_switch_actions(java_source: str) -> list[str]:return out-def extract_rest_actions(java_source: str) -> list[str]:- """ucfirst(method name) of @GET/@POST/@PUT/@DELETE/@PATCH methods, source order.+CLASS_EXTENDS_RE = re.compile(r"public\s+(?:abstract\s+)?class\s+\w+\s+extends\s+([A-Za-z0-9_]+)")- Only applies to classes containing a class-level @Path. Returns [] otherwise.- """- if not CLASS_PATH_RE.search(java_source):- return []++def _extract_raw_rest_methods(java_source: str) -> list[str]:actions: list[str] = []pending = Falsefor line in java_source.splitlines():@@ -119,6 +116,26 @@ def extract_rest_actions(java_source: str) -> list[str]:return actions+def extract_rest_actions(java_source: str, source_path: Path | None = None) -> list[str]:+ """ucfirst(method name) of @GET/@POST/@PUT/@DELETE/@PATCH methods, source order.++ Only applies to classes containing a class-level @Path. Returns [] otherwise.+ Inherited methods from a superclass in the same directory are included first.+ """+ if not CLASS_PATH_RE.search(java_source):+ return []+ actions: list[str] = []+ if source_path is not None:+ extends_match = CLASS_EXTENDS_RE.search(java_source)+ if extends_match:+ super_name = extends_match.group(1)+ super_path = source_path.parent / f"{super_name}.java"+ if super_path.exists():+ actions.extend(_extract_raw_rest_methods(super_path.read_text(encoding="utf-8")))+ actions.extend(_extract_raw_rest_methods(java_source))+ return actions++def extract_actions(entry: ServiceEntry) -> list[str]:"""Merged, deduped, override-corrected action list for a service.@@ -133,7 +150,7 @@ def extract_actions(entry: ServiceEntry) -> list[str]:if source.mode == "switch":raw = extract_switch_actions(text)elif source.mode == "rest":- raw = extract_rest_actions(text)+ raw = extract_rest_actions(text, source.path)else:raise ValueError(f"unknown mode: {source.mode!r}")for name in raw:diff --git a/tools/docs/test_regen_action_docs.py b/tools/docs/test_regen_action_docs.pyindex 11540830b5..9689538f37 100644--- a/tools/docs/test_regen_action_docs.py+++ b/tools/docs/test_regen_action_docs.py@@ -130,6 +130,32 @@ public class C {assert r.extract_rest_actions(src) == ["CreateThing", "ListThings"]+def test_extract_rest_inherits_methods_from_superclass(tmp_path: Path):+ base_src = """+public abstract class BaseController {+ @GET+ public Response getBaseItem() { return ok(); }++ @DELETE+ public Response deleteBaseItem() { return ok(); }+}+"""+ sub_src = """+@Path("/items")+public class ChildController extends BaseController {+ @POST+ public Response createChildItem() { return ok(); }+}+"""+ base_file = tmp_path / "BaseController.java"+ sub_file = tmp_path / "ChildController.java"+ base_file.write_text(base_src, encoding="utf-8")+ sub_file.write_text(sub_src, encoding="utf-8")++ actions = r.extract_rest_actions(sub_src, sub_file)+ assert actions == ["GetBaseItem", "DeleteBaseItem", "CreateChildItem"]++def test_extract_actions_applies_rename_and_exclude(tmp_path: Path):src = tmp_path / "ThingController.java"src.write_text(REST_CONTROLLER)