diff --git a/content/topics/java/topic.md b/content/topics/java/topic.md index ec28749..10f2c37 100644 --- a/content/topics/java/topic.md +++ b/content/topics/java/topic.md @@ -16,6 +16,7 @@ childTopicIds: - '750d6258-e1be-4813-9487-18c6ba78af0a' - '57b0dc57-7a64-4c09-9140-2a470748da38' - '78b29290-d46f-45b2-aaba-c31597ceb6d4' + - 'de9bf772-5146-4995-a438-161b5ad229d2' relatedTopicIds: - '0eab5dfb-d4ab-4cf8-a56c-41b4548da56c' --- diff --git a/content/topics/spring-api-errors/sources.md b/content/topics/spring-api-errors/sources.md new file mode 100644 index 0000000..544b485 --- /dev/null +++ b/content/topics/spring-api-errors/sources.md @@ -0,0 +1,16 @@ +# Handle API errors in Spring — authoring sources + +Retrieval job: map failures reaching Spring MVC to deliberate HTTP statuses and +a consistent response body. Checked 2026-10-27 against Spring Framework 7 docs. + +- [Controller advice](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-advice.html): bean registration, default controller scope, narrowing selectors, and `@ResponseBody` composition. +- [Exception handlers](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html): matching exception types and returning `ResponseEntity`. +- [MVC request-body arguments](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html): Bean Validation failures and default HTTP 400 behavior. +- [Spring MVC default exception resolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.html): default status mapping for unreadable request bodies. +- [Error responses](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-ann-rest-exceptions.html): `ProblemDetail`, RFC 9457 fields, the default request path for `instance`, and avoiding disclosure of implementation details. +- [RFC 9110 — status codes](https://www.rfc-editor.org/rfc/rfc9110.html#name-status-codes): 400, 404, 409, and 500 semantics. + +The local `spring-boot-api-practice` exercise supplies the concrete names +`ApiError`, `ApiExceptionHandler`, `ProductNotFoundException`, and +`DuplicateSkuException`. The example is intentionally smaller than its handler; +it does not reproduce the exercise's broad `IllegalArgumentException` mapping. diff --git a/content/topics/spring-api-errors/topic.md b/content/topics/spring-api-errors/topic.md new file mode 100644 index 0000000..af6ebe9 --- /dev/null +++ b/content/topics/spring-api-errors/topic.md @@ -0,0 +1,90 @@ +--- +id: '973352f3-ac82-42a1-a38a-5c09e3946de0' +title: 'Handle API errors in Spring' +status: 'accepted' +iconKey: 'operations' +domains: + - 'java' + - 'http' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - '31ee0d58-0999-457e-9d7c-5fe20ef9be56' + - 'b97384d3-f986-4850-a6b0-a1c3b893ee86' +--- + +## Map an exception to a response + +```java +record ApiError(String message) {} + +@RestControllerAdvice +public class ApiExceptionHandler { + @ExceptionHandler(ProductNotFoundException.class) + public ResponseEntity handleNotFound( + ProductNotFoundException ex) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ApiError("Product not found")); + } +} +``` + +`ProductNotFoundException` is an application exception. This example handles +**only that failure**; add handlers for other failures the API needs to format. + +**JSON body:** `{ "message": "Product not found" }`. + +| Piece | Role | +| -------------------------- | ------------------------------------- | +| `@RestControllerAdvice` | **Shared handlers** + response bodies | +| `@ExceptionHandler(...)` | Match the **exception type** | +| `ResponseEntity` | **Status, headers, and body** | +| `ApiError` | Your **custom response body type** | + +## Choose the status by failure + +| Failure | Exception / example | HTTP | +| -------------------- | ----------------------------------- | ------- | +| DTO body validation | `MethodArgumentNotValidException` | **400** | +| JSON/type conversion | `HttpMessageNotReadableException` | **400** | +| Missing product | `ProductNotFoundException` | **404** | +| SKU already in use | `DuplicateSkuException` | **409** | +| Unexpected failure | Programming or infrastructure error | **500** | + +These are deliberate API mappings. **Custom exception names do not assign HTTP +statuses.** For DTO failures, get field errors from `ex.getBindingResult()`. + +> For unexpected failures, **log the diagnostic details** and return a **safe +> client message**. Avoid forwarding arbitrary exception messages or treating +> every `IllegalArgumentException` as a client error. + +## Place and scope the handler + +- Put **API-wide error handling** (`ApiExceptionHandler`) and its **response body + type** (`ApiError`) in an `error` package alongside feature packages such as + `product`. Keep product-specific exceptions with `product`. +- Register the advice as a **Spring bean**, usually through component scanning. + The package name does not set its scope: advice applies to **all controllers by + default**; annotation selectors can narrow it. +- **Jobs and calls outside Spring MVC** need their own error handling. Advice + handles exceptions reaching MVC's exception resolution. + +## Use Spring's built-in error body + +Instead of defining `ApiError`, you can use **`ProblemDetail`**, Spring's type for +a standard HTTP error response: + +```json +{ + "type": "about:blank", + "title": "Not Found", + "status": 404, + "detail": "Product not found", + "instance": "/products/42" +} +``` + +**The handler still selects the exception and builds the response.** +`ProblemDetail` supplies the body format. + +**`instance`:** Spring MVC uses the current request path when this field is unset. diff --git a/content/topics/spring-bean-validation/sources.md b/content/topics/spring-bean-validation/sources.md new file mode 100644 index 0000000..6701b98 --- /dev/null +++ b/content/topics/spring-bean-validation/sources.md @@ -0,0 +1,10 @@ +# Bean Validation in Spring — authoring sources + +References for verifying future edits to `topic.md`. This file is not rendered +in the application. + +- [Spring MVC: request body validation](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html) +- [Spring Boot: service method validation](https://docs.spring.io/spring-boot/reference/io/validation.html) +- [Jakarta: positive numbers and null](https://jakarta.ee/specifications/bean-validation/3.0/apidocs/jakarta/validation/constraints/Positive.html) +- [Hibernate Validator: declaring and executing validation](https://docs.hibernate.org/validator/9.0/reference/en-US/html_single/) +- [Spring: proxy invocation](https://docs.spring.io/spring-framework/reference/core/aop/proxying.html) diff --git a/content/topics/spring-bean-validation/topic.md b/content/topics/spring-bean-validation/topic.md new file mode 100644 index 0000000..5a0f084 --- /dev/null +++ b/content/topics/spring-bean-validation/topic.md @@ -0,0 +1,74 @@ +--- +id: '31ee0d58-0999-457e-9d7c-5fe20ef9be56' +title: 'Bean Validation in Spring' +status: 'accepted' +iconKey: 'operations' +domains: + - 'java' + - 'http' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - '973352f3-ac82-42a1-a38a-5c09e3946de0' + - '9e290750-ab85-4acb-bca2-88d7ad758cd7' +--- + +## Validate an incoming body + +With `spring-boot-starter-validation` on the classpath: + +```java +record CreateItem( + @NotBlank String name, + @NotNull @Positive BigDecimal price) {} + +// Spring MVC controller parameter: +// @Valid @RequestBody CreateItem input +``` + +Spring MVC deserializes the body, then validates its constraints. For this parameter +shape, a failure raises `MethodArgumentNotValidException` and produces **400 by +default**. Customize exception handling for the API's error body. + +Malformed JSON fails during deserialization, before Bean Validation; handle that +failure too when providing a consistent error response. + +## Choose the constraint + +| Annotation | Checks | Rejects `null`? | +| ----------------------------- | ------------------------------------------------- | --------------- | +| `@NotNull` | Value is not `null` | Yes | +| `@NotBlank` | String contains a non-whitespace character | Yes | +| `@Size(min = 1, max = 32)` | String length or container size, inclusive bounds | No | +| `@Positive` | Number is strictly greater than zero | No | +| `@Pattern(regexp = "[A-Z]+")` | String matches the regular expression | No | + +**Required positive price:** combine `@NotNull` and `@Positive`. +**Whitespace:** these annotations do not trim input; `@Size` checks the value it +receives. + +## What actually runs validation? + +| Call path | Activation | +| ------------------------------ | --------------------------------------------- | +| MVC request body | `@Valid @RequestBody` | +| Spring bean method | `@Validated` class + `@Valid` object argument | +| Explicit Java call | `Validator.validate(object)` | +| Ordinary `new CreateItem(...)` | No automatic annotation checks | + +> **Constraint annotations declare rules; validation needs an execution path.** +> A constructor needs explicit checking code to reject invalid arguments on an +> ordinary `new` call. + +For explicit validation, a non-empty result means the object failed its constraints; +`validate` itself returns violations rather than throwing for invalid field values: + +```java +// validator is an injected jakarta.validation.Validator. +var violations = validator.validate(input); +``` + +- Spring method validation requires a call **through the proxy**; `this` calls bypass it. +- For nested objects, `@Valid` cascades into their constraints; add `@NotNull` if + the nested object itself is required. +- Bean Validation failures outside MVC do not automatically mean HTTP 400. diff --git a/content/topics/spring-boot-create-run/sources.md b/content/topics/spring-boot-create-run/sources.md new file mode 100644 index 0000000..2ac31be --- /dev/null +++ b/content/topics/spring-boot-create-run/sources.md @@ -0,0 +1,31 @@ +# Create and run a Spring Boot app — authoring sources + +Retrieval job: recover the generation choices, local run commands, and controller +syntax for creating and retrieving a resource. Checked 2026-10-28. + +- [IntelliJ Spring Boot project wizard](https://www.jetbrains.com/help/idea/spring-initializr-project-wizard.html): menu path, shared project settings, dependencies, and default Initializr service. +- [Spring Initializr reference](https://docs.spring.io/initializr/docs/current/reference/html/): project-generation service and metadata. +- [Spring Initializr service](https://start.spring.io/): browser generator. The verification fixture was generated by this service with Boot 4.1.2, Java 21, Maven, `ProductsApplication`, and Web MVC/Validation dependencies. +- [Run a Spring Boot application](https://docs.spring.io/spring-boot/reference/using/running-your-application.html): IDE, Maven plugin, executable JAR, and duplicate-port behavior. +- [Actuator endpoints](https://docs.spring.io/spring-boot/reference/actuator/endpoints.html): built-in health endpoint, default HTTP exposure, and health indicator aggregation. +- [Managed dependency coordinates](https://docs.spring.io/spring-boot/appendix/dependency-versions/coordinates.html): managed `org.springframework.boot:spring-boot-starter-actuator` dependency. Also present in the local exercise's Maven configuration. +- [IntelliJ Spring application example](https://www.jetbrains.com/help/idea/your-first-spring-application.html): generated main class, running it, and default HTTP port 8080. +- [Structure Spring Boot code](https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html): root application package and default scanning. +- [MVC request mappings](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html): REST controller, HTTP method mappings, and path variables. +- [MVC request body](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html): JSON deserialization and `@Valid`. +- [ResponseEntity API](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html): `created(URI)` sets HTTP 201 and the Location header. + +The controller and record shapes are adapted from the local +`spring-boot-api-practice` exercise. The Topic deliberately shows only the web +boundary, assuming the exercise's service contract and Product getters; it is +not a complete standalone CRUD application. Imports are omitted from snippets. + +The authored controller and records were compiled in the generated project with +the exercise's service/repository/model, adapting packages and adding imports. +Both the packaged JAR and Maven development run returned POST 201 with Location +and GET 200 with the matching product JSON. Verified on JDK 25 targeting Java 21. + +The Actuator dependency was also checked in a fresh generated app with no +controllers or custom exposure settings. `/actuator/health` returned HTTP 200 +with `status: UP` and additional health-group fields; the Topic intentionally +checks the status rather than prescribing an exact response object. diff --git a/content/topics/spring-boot-create-run/topic.md b/content/topics/spring-boot-create-run/topic.md new file mode 100644 index 0000000..b33f21a --- /dev/null +++ b/content/topics/spring-boot-create-run/topic.md @@ -0,0 +1,128 @@ +--- +id: '2eae671e-54ad-4afa-b85f-26415d0cea59' +title: 'Create and run a Spring Boot app' +status: 'accepted' +iconKey: 'operations' +domains: + - 'java' + - 'http' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - '31ee0d58-0999-457e-9d7c-5fe20ef9be56' + - '973352f3-ac82-42a1-a38a-5c09e3946de0' +--- + +## Create the skeleton + +| Method | Generate the project | +| -------------- | ---------------------------------------------------------- | +| **IntelliJ** | File → New → Project → **Spring Boot** | +| **Initializr** | [start.spring.io](https://start.spring.io/) → **Generate** | + +IntelliJ's wizard uses **Spring Initializr**. For these examples, choose **Java 21 · +Maven · JAR**, a released Boot version, and dependencies **Spring Web + Validation**. + +**Name:** `Products` · **Artifact:** `products` · **Group:** `com.example` · +**Package:** `com.example.products`. + +For a downloaded ZIP, extract it and open the folder containing `pom.xml` as a +Maven project in IntelliJ. + +## Run the app + +Run terminal commands from **the project root** (`products/`, containing `pom.xml` +and `mvnw`). + +| From | Start the application | +| ------------ | ---------------------------------------------- | +| **IntelliJ** | Run the generated `ProductsApplication.main()` | +| **Terminal** | `./mvnw spring-boot:run` | + +### Check health with Actuator + +Select **Spring Boot Actuator** in Initializr, or add this dependency inside +`pom.xml`'s ``: + +```xml + + org.springframework.boot + spring-boot-starter-actuator + +``` + +**Run or restart** the app, then check: + +```bash +curl http://localhost:8080/actuator/health +``` + +**Healthy response:** includes `"status": "UP"`; additional fields may appear. + +Health is **exposed by default**; **no custom controller is required**. +`UP` reflects the configured health checks; it does not verify product endpoints. + +### Run a packaged JAR + +```bash +./mvnw package +java -jar target/products-0.0.1-SNAPSHOT.jar +``` + +`spring-boot:run` runs from the project; **`java -jar` runs the built artifact**. +Rebuild the JAR after changing source code. + +## Create and fetch a product + +| Request | Successful response | +| -------------------- | ------------------------------------------- | +| `POST /products` | **201 Created** + `Location` + product body | +| `GET /products/{id}` | **200 OK** + product body | + +> Keep the controller and service **in or below the application's root package** +> (`com.example.products`) so default component scanning finds them. + +### Request and response records + +```java +record CreateProductRequest( + @NotBlank String sku, + @NotBlank String name, + @NotNull @Positive BigDecimal price) {} + +record ProductResponse( + UUID id, String sku, String name, BigDecimal price) {} +``` + +### Controller + +```java +@RestController +@RequestMapping("/products") +public class ProductController { + private final ProductService service; + + public ProductController(ProductService service) { + this.service = service; + } + + @PostMapping + public ResponseEntity create( + @Valid @RequestBody CreateProductRequest input) { + Product product = service.create(input); + URI location = URI.create("/products/" + product.getId()); + return ResponseEntity.created(location) + .body(toResponse(product)); + } + + @GetMapping("/{id}") + public ProductResponse get(@PathVariable("id") UUID id) { + return toResponse(service.get(id)); + } + + private ProductResponse toResponse(Product product) { + return new ProductResponse(product.getId(), product.getSku(), + product.getName(), product.getPrice()); + } +} +``` diff --git a/content/topics/spring-boot/sources.md b/content/topics/spring-boot/sources.md new file mode 100644 index 0000000..90600cc --- /dev/null +++ b/content/topics/spring-boot/sources.md @@ -0,0 +1,18 @@ +# Spring and Spring Boot — authoring sources + +References for verifying `topic.md`; not rendered in the application. Checked +2026-10-27. The Topic compares Spring with and without Boot, rather than specific +Framework or Boot major versions. + +- [Spring Framework overview](https://docs.spring.io/spring-framework/reference/overview.html): the Spring family, core container, optional modules, and web/non-web application scenarios. +- [Spring Framework project](https://spring.io/projects/spring-framework/): infrastructure, dependency injection, transactions, data-access integration, and testing support. +- [Spring MVC](https://docs.spring.io/spring-framework/reference/web/webmvc.html): Servlet-based web framework within Spring Framework. +- [Spring Data](https://spring.io/projects/spring-data/): separate project family providing repository and data-access abstractions. +- [Spring Security](https://spring.io/projects/spring-security/): separate project providing authentication and authorization. +- [Spring Integration](https://spring.io/projects/spring-integration/): message flows, enterprise integration patterns, and adapters for external systems. +- [Spring Batch](https://spring.io/projects/spring-batch/): batch processing, job restart, retry, and Boot integration. +- [Spring Boot project](https://spring.io/projects/spring-boot/): starters, auto-configuration, embedded servers, executable applications, and production features. +- [Boot dependency management and starters](https://docs.spring.io/spring-boot/reference/using/build-systems.html): managed dependency versions and dependency descriptors. +- [Boot auto-configuration](https://docs.spring.io/spring-boot/reference/using/auto-configuration.html): conditional defaults and replacing them with application configuration. +- [Spring Java configuration](https://docs.spring.io/spring-framework/reference/core/beans/java.html): annotation-based configuration is available independently of Boot. +- [Boot traditional deployment](https://docs.spring.io/spring-boot/how-to/deployment/traditional-deployment.html): Servlet applications can use external-container WAR deployment as an alternative to an embedded server. diff --git a/content/topics/spring-boot/spring-ecosystem.svg b/content/topics/spring-boot/spring-ecosystem.svg new file mode 100644 index 0000000..1098411 --- /dev/null +++ b/content/topics/spring-boot/spring-ecosystem.svg @@ -0,0 +1,76 @@ + + Spring Framework modules and separate Spring projects + Spring Framework contains core container, data access and transaction, web, and testing modules. MVC and WebFlux belong to its web support. Separate projects including Spring Data, Security, Integration, and Batch build on the Framework. Spring Boot is optional and helps configure and run applications using the selected modules and projects. These are selected examples, not a complete inventory. + + + + + + + + + Spring Framework + Selected parts inside it + + + Core container + DI · lifecycle + + + Data access + JDBC / ORM + Transactions + + + Web + MVC · Servlet + WebFlux · reactive + + + Testing + TestContext + MockMvc + + + Other projects + Separate from Framework + + + Spring Data + Repositories + + + Spring Security + Authentication + Authorization + + + Spring Integration + Message flows + System adapters + + + Spring Batch + Batch jobs + Restart · retry + + + build on + + + + + + Spring Boot (optional) + Starters · auto-configuration + Application launch · packaging + Helps configure your chosen pieces. + diff --git a/content/topics/spring-boot/topic.md b/content/topics/spring-boot/topic.md new file mode 100644 index 0000000..bd8991f --- /dev/null +++ b/content/topics/spring-boot/topic.md @@ -0,0 +1,52 @@ +--- +id: 'de9bf772-5146-4995-a438-161b5ad229d2' +title: 'Spring and Spring Boot' +status: 'accepted' +summary: 'Distinguish Spring Framework, MVC, and Boot; see what Boot automates.' +iconKey: 'network' +domains: + - 'java' +kind: 'area' +childTopicIds: + - '2eae671e-54ad-4afa-b85f-26415d0cea59' + - '31ee0d58-0999-457e-9d7c-5fe20ef9be56' + - '973352f3-ac82-42a1-a38a-5c09e3946de0' +relatedTopicIds: [] +--- + +## Framework, other projects, and Boot + +![Spring Framework contains core container, data-access, web, and testing modules; MVC and WebFlux are part of its web support. Separate projects Spring Data, Security, Integration, and Batch build on the Framework. Optional Spring Boot helps configure and run applications using the selected pieces.](./spring-ecosystem.svg) + +**MVC and Boot work together.** MVC handles web requests; Boot sets up the +application around it. Boot also supports **non-web applications**. + +## Why use Spring? + +- Dependency injection: Spring **creates and connects components**, reducing + manual wiring. +- Shared infrastructure: reuse transaction, web, data-access, and testing support; + **your code supplies business rules**. +- Trade-off: adopt a **framework lifecycle and configuration conventions**. + Small programs may not need that infrastructure. + +## Spring without Boot vs with Boot + +| Spring without Boot | What Boot adds | +| -------------------------- | ---------------------------------- | +| Choose dependency versions | **Managed versions + starters** | +| Configure infrastructure | **Conditional auto-configuration** | +| Set up web deployment | **Embedded server + runnable JAR** | + +These are common web-application setup choices. Boot's defaults can be +**overridden**; an embedded server is not the only deployment option. + +Spring without Boot can use **Java configuration and annotations**, not just XML. +Boot reduces setup work; it does not replace Spring Framework or MVC. + +## What Spring does not supply + +- **A language, JVM, or database:** Spring integrates with these technologies. +- **Your business rules:** you still write and test application behavior. +- **A required microservice architecture:** Spring and Boot also support monoliths + and batch applications. diff --git a/content/topics/system-design/topic.md b/content/topics/system-design/topic.md index f366b78..99409bd 100644 --- a/content/topics/system-design/topic.md +++ b/content/topics/system-design/topic.md @@ -16,6 +16,7 @@ childTopicIds: - '4f4a4da6-3a42-4e60-b3b3-8669ba57cf70' - '92179879-7f1c-49b1-8751-cf296302bb82' - '4aa75f9e-93ce-46e3-80d7-ac13d14a77c0' + - '0e57098c-0ac7-4b9a-8123-80d696abaa6a' relatedTopicIds: - 'fa8a91df-3ad6-4a30-bba7-34ea42c9b1ac' --- diff --git a/content/topics/validation-boundaries/shared-entry-paths.svg b/content/topics/validation-boundaries/shared-entry-paths.svg new file mode 100644 index 0000000..6708923 --- /dev/null +++ b/content/topics/validation-boundaries/shared-entry-paths.svg @@ -0,0 +1,55 @@ + + Shared validation paths for HTTP and other callers + HTTP requests pass through controller and DTO validation. Jobs and CLI callers enter the shared application operation directly. The operation trims SKU and name before checking, constructs domain values with invariant checks, and checks current application state. Storage enforces uniqueness at the write. This is an illustrative creation flow. + + + + + + + + + HTTP / DTO + Required · format + @Valid + + + Job / CLI + No controller + + + + + + Shared application operation + Trim SKU and name before checking + + + Construct valid domain values + Positive price · valid SKU + Constructor / factory + + + + + Check application state + SKU unused · stock available + Service + storage lookup + + + + + Enforce rules at the write + Unique SKU across writers + Unique constraint / atomic write + + Illustrative create flow + Reject before side effects + diff --git a/content/topics/validation-boundaries/topic.md b/content/topics/validation-boundaries/topic.md new file mode 100644 index 0000000..a7ee8b3 --- /dev/null +++ b/content/topics/validation-boundaries/topic.md @@ -0,0 +1,68 @@ +--- +id: '0e57098c-0ac7-4b9a-8123-80d696abaa6a' +title: 'Where validation belongs' +status: 'accepted' +iconKey: 'validation' +domains: + - 'system-design' +kind: 'decision-aid' +childTopicIds: + - '31ee0d58-0999-457e-9d7c-5fe20ef9be56' +relatedTopicIds: + - '64c5e924-a8ca-4aca-837e-d3b84c5ea1a6' + - '8dd9f085-233c-4256-a012-717137df5473' +--- + +## Choose who owns the guarantee + +![HTTP requests pass through controller and DTO validation; jobs and CLI callers enter the shared application operation directly. The shared operation trims SKU and name before checking, constructs domain values with invariant checks, and checks current application state. Storage enforces uniqueness at the write.](./shared-entry-paths.svg) + +Isolation-based checks need **only the supplied values**, including relationships +between fields. State-dependent checks need **application data** and can become +**outdated before a write**. + +## Reject early, protect every entry point + +> Reject at the **earliest point with enough information**, **before side effects**. + +- Enforce guarantees needed by every caller in the **shared operation or domain type**. +- Protect object invariants during **construction and mutation**. +- Use an early uniqueness lookup for **feedback**. Concurrent requests may both + pass it, so enforce uniqueness **at the write**. + +## Normalize consistently + +For a contract that trims surrounding whitespace: + +```text +" BOOK-001 " → "BOOK-001" +``` + +Use the **same trimmed value** for **length checks, uniqueness lookup, and storage**. + +- Checking raw length can **reject valid padded input**. +- Comparing raw SKUs can **miss a duplicate**. + +## When to share validation + +| Situation | Approach | +| ------------------------------------ | ---------------------------------------- | +| Callers share the **same invariant** | Reuse **one implementation of the rule** | +| Different **operation requirements** | Use **operation-specific validation** | + +Creation may **require a name**; a partial update may **omit it**. Any supplied name +must still satisfy the **shared name rules**. + +When the same rule is enforced in several places, **keep the checks consistent**. +For example, the DTO and domain constructor should agree on the SKU length limit. + +### Where to put a validation method + +| Method location | Typical fit | +| -------------------------- | ---------------------------------------------------- | +| **Static utility** | **Supplied values only**; reuse across components | +| **Injected bean** | Shared checks need **a repository or configuration** | +| **Private service method** | Reuse **within that service only** | + +Alternatively, use a **type that validates during construction** to enforce the +rule whenever an instance is created. diff --git a/contracts/runtime-catalog.ts b/contracts/runtime-catalog.ts index b6eca6e..a500d72 100644 --- a/contracts/runtime-catalog.ts +++ b/contracts/runtime-catalog.ts @@ -21,6 +21,8 @@ export const TOPIC_ICON_KEYS = [ 'equality', 'ordering', 'persistence', + 'network', + 'validation', ] as const; export type TopicIconKey = (typeof TOPIC_ICON_KEYS)[number]; diff --git a/docs/content-authoring.md b/docs/content-authoring.md index a0aaeff..56c9790 100644 --- a/docs/content-authoring.md +++ b/docs/content-authoring.md @@ -123,6 +123,26 @@ may reveal that it contains several retrieval jobs. - Put deeper or adjacent material in child Topics instead of expanding the current Topic indefinitely. +## Keep verification sources in an authoring-only file + +For new Topics, preserve sources useful for verifying future edits in +`content/topics//sources.md`, alongside `topic.md`. Do not add a reader-facing +Sources, References, or bibliography section merely to record the author's research. + +- Keep source titles and direct URLs. Add a short note about the supported claim, + section, or version only when it helps future verification. +- Create `sources.md` only when there are useful references to retain; do not add an + empty file or a generic reading list. +- Keep it separate from the Topic body and front matter. The generator discovers + `topic.md`; `sources.md` is not rendered in the application or bundled as Topic + content. +- Include an external link in the Topic itself only when following it directly + serves the reader's retrieval job. Provenance alone belongs in `sources.md`. + +The [Bean Validation in Spring authoring sources](../content/topics/spring-bean-validation/sources.md) +show this convention. This rule applies to new Topics; it does not require a bulk +migration of existing source sections. + ## Choose the fastest representation Use the representation that makes the information fastest to recognize: @@ -257,8 +277,10 @@ Before presenting a draft for retrieval evaluation or reviewing a revision: another representation. 8. Remove introductions, transitions, repetition, and summaries that do not make a specific lookup easier. -9. Check the rendered Topic at wide and narrow viewport sizes. -10. Run the repository verification required by the +9. For new Topics, confirm that any retained verification references are in + `sources.md` and links in the Topic body serve the reader's retrieval job. +10. Check the rendered Topic at wide and narrow viewport sizes. +11. Run the repository verification required by the [AI-assisted development profile](ai-assisted-development.md). These checks support readiness for retrieval evaluation. Editorial promotion remains diff --git a/docs/content-storage.md b/docs/content-storage.md index ef3865d..0847563 100644 --- a/docs/content-storage.md +++ b/docs/content-storage.md @@ -54,6 +54,7 @@ content/ │ └── topic.md ├── queue/ │ ├── topic.md + │ ├── sources.md │ └── queue-operations.svg └── queue-complexity/ └── topic.md @@ -64,6 +65,10 @@ must contain a `topic.md` file. Topic directories are peers; they do not mirror the navigation hierarchy because the content model permits a Topic to have multiple parents. +An optional `sources.md` beside `topic.md` holds authoring references for future +verification, following the [content authoring guide](content-authoring.md). It is +not discovered as a Topic, rendered, or bundled as Topic content. + Directory names are unique, human-readable storage labels. They are not Topic identifiers, do not appear in relationships, and do not need to change when a Topic title changes. Contextual names such as `queue-complexity` and @@ -139,9 +144,21 @@ Two presentation properties are optional for a Topic generally: The supported icon keys are `java`, `architecture`, `algorithm`, `database`, `array`, `collection`, `conversion`, `copy`, `creation`, `deque`, `heap`, `list`, `map`, `operations`, `priority`, `queue`, `set`, `complexity`, `concurrency`, -`equality`, `ordering`, and `persistence`. Topics may reuse a key. Extending this -closed vocabulary is a deliberate shared-contract change rather than an ordinary -content edit. +`equality`, `ordering`, `persistence`, `network`, and `validation`. Topics may +reuse a key. Extending this closed vocabulary is a deliberate shared-contract +change rather than an ordinary content edit. + +The subject-specific keys provide distinct recognition within a technical domain: + +| Key | Symbol | Typical subject | +| --- | --- | --- | +| `network` | Connected components | System architecture | +| `validation` | Checklist | Validation rules | + +These assets use the selected Lucide 1.17.0 glyphs with the application's stroke +width and accent colors. Their license notice ships alongside them at +`public/icons/topics/lucide-LICENSE.txt`; the renderer loads local SVGs without a +runtime icon-library dependency. The supported domain keys, in canonical generated and display order, are `java`, `collections`, `concurrency`, `persistence`, `databases`, `http`, diff --git a/docs/visual-design.md b/docs/visual-design.md index 6a57ccb..8bd04e2 100644 --- a/docs/visual-design.md +++ b/docs/visual-design.md @@ -84,6 +84,10 @@ so the destinations are easier to recognize. Color does not carry classification meaning by itself. A Topic icon key likewise receives a consistent default treatment in the UI. +The network symbol provides a reusable architecture cue; the checklist symbol +identifies validation rules. Topic icons remain semantic catalog keys rather than +title- or hierarchy-specific renderer choices. + ### Typography Typography supplies much of the interface's hierarchy: diff --git a/public/icons/topics/lucide-LICENSE.txt b/public/icons/topics/lucide-LICENSE.txt new file mode 100644 index 0000000..718bb3f --- /dev/null +++ b/public/icons/topics/lucide-LICENSE.txt @@ -0,0 +1,43 @@ +ISC License + +Copyright (c) 2026 Lucide Icons and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--- + +The following Lucide icons are derived from the Feather project: + +airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out + +The MIT License (MIT) (for the icons listed above) + +Copyright (c) 2013-present Cole Bemis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/public/icons/topics/network.svg b/public/icons/topics/network.svg new file mode 100644 index 0000000..fcba53e --- /dev/null +++ b/public/icons/topics/network.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/public/icons/topics/validation.svg b/public/icons/topics/validation.svg new file mode 100644 index 0000000..d439bb7 --- /dev/null +++ b/public/icons/topics/validation.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/src/app/browse/topic-index-page.spec.ts b/src/app/browse/topic-index-page.spec.ts index 406aefd..6afe1a9 100644 --- a/src/app/browse/topic-index-page.spec.ts +++ b/src/app/browse/topic-index-page.spec.ts @@ -39,7 +39,7 @@ describe('TopicIndexPage', () => { host.querySelectorAll('.domain-hierarchy__root > .domain-hierarchy__item app-topic-icon'), ).map((icon) => icon.getAttribute('data-icon-key')), ).toEqual(['java', 'architecture', 'architecture', 'database', 'architecture']); - expect(host.querySelector('[role="status"]')?.textContent).toContain('105 topics'); + expect(host.querySelector('[role="status"]')?.textContent).toContain('110 topics'); }); it('renders the default System Design view as an expandable hierarchy', async () => { @@ -81,6 +81,7 @@ describe('TopicIndexPage', () => { 'Cache loading and write strategies', 'Cache freshness and removal', 'Spring caching with Redis', + 'Where validation belongs', 'Choosing a database', 'Database data models', 'Comparing database engines', @@ -95,7 +96,7 @@ describe('TopicIndexPage', () => { 'Atomic creation — PostgreSQL', ]); expect((host.querySelector('#topic-domain') as HTMLSelectElement).value).toBe('system-design'); - expect(host.querySelector('[role="status"]')?.textContent).toContain('36 topics'); + expect(host.querySelector('[role="status"]')?.textContent).toContain('37 topics'); }); it('shows draft topics and clears every constraint', async () => { diff --git a/src/app/catalog/catalog.service.spec.ts b/src/app/catalog/catalog.service.spec.ts index df08154..399c002 100644 --- a/src/app/catalog/catalog.service.spec.ts +++ b/src/app/catalog/catalog.service.spec.ts @@ -104,8 +104,8 @@ describe('CatalogService', () => { 'system-design', 'algorithms-data-structures', ]); - expect(service.getDomainTopicCount('system-design')).toBe(36); - expect(service.getDomainTopicCount('http')).toBe(15); + expect(service.getDomainTopicCount('system-design')).toBe(37); + expect(service.getDomainTopicCount('http')).toBe(18); expect(service.getKindOptions().map(({ key }) => key)).toEqual([ 'area', 'concept', @@ -218,7 +218,7 @@ describe('CatalogService', () => { const view = service.getTopicBrowseView({ query: '', domain: null, kind: null, status: null }); expect(view.mode).toBe('hierarchy'); - expect(view.resultCount).toBe(105); + expect(view.resultCount).toBe(110); expect(view.sections).toEqual([]); expect(view.hierarchyRoots.map(({ title }) => title)).toEqual([ 'Java', @@ -235,7 +235,7 @@ describe('CatalogService', () => { expect(occurrences).toHaveLength(2); expect(occurrences.every(({ id }) => id === STREAMS_TOPIC_ID)).toBe(true); - expect(roots[0].matchingTopicCount).toBe(60); + expect(roots[0].matchingTopicCount).toBe(64); }); it('intersects domain and kind filters', () => { @@ -260,7 +260,7 @@ describe('CatalogService', () => { status: null, }); - expect(view.resultCount).toBe(36); + expect(view.resultCount).toBe(37); expect(view.mode).toBe('hierarchy'); expect(view.sections).toEqual([]); expect(view.hierarchyRoots.map(({ title }) => title)).toEqual([ @@ -274,7 +274,7 @@ describe('CatalogService', () => { 'Relational databases (SQL)', 'Managed vs self-managed databases', ]); - expect(view.hierarchyRoots[0].matchingTopicCount).toBe(23); + expect(view.hierarchyRoots[0].matchingTopicCount).toBe(24); expect(view.hierarchyRoots[0].children.map(({ title }) => title)).toEqual([ 'Messaging', 'Scale and estimation', @@ -284,6 +284,7 @@ describe('CatalogService', () => { 'Pagination: offset vs cursor', 'Content delivery networks (CDNs)', 'Shared caching', + 'Where validation belongs', ]); }); @@ -297,15 +298,20 @@ describe('CatalogService', () => { expect(view.mode).toBe('hierarchy'); expect(view.hierarchyRoots.map(({ title }) => title)).toEqual([ + 'Java', 'System Design', 'HTTP', 'Idempotency keys', ]); expect(view.hierarchyRoots[0].matchesDomain).toBe(false); expect(view.hierarchyRoots[0].children.map(({ title }) => title)).toEqual([ - 'Content delivery networks (CDNs)', + 'Spring and Spring Boot', ]); expect(view.hierarchyRoots[1].children.map(({ title }) => title)).toEqual([ + 'Content delivery networks (CDNs)', + 'Where validation belongs', + ]); + expect(view.hierarchyRoots[2].children.map(({ title }) => title)).toEqual([ 'HTTP status codes', ]); }); @@ -364,6 +370,7 @@ describe('CatalogService', () => { '750d6258-e1be-4813-9487-18c6ba78af0a', '57b0dc57-7a64-4c09-9140-2a470748da38', '78b29290-d46f-45b2-aaba-c31597ceb6d4', + 'de9bf772-5146-4995-a438-161b5ad229d2', ]); }); diff --git a/src/app/ui/topic-icon/topic-icon.css b/src/app/ui/topic-icon/topic-icon.css index ced662a..9e9cd8d 100644 --- a/src/app/ui/topic-icon/topic-icon.css +++ b/src/app/ui/topic-icon/topic-icon.css @@ -20,7 +20,8 @@ img { } :host([data-icon-key='architecture']), -:host([data-icon-key='concurrency']) { +:host([data-icon-key='concurrency']), +:host([data-icon-key='network']) { --topic-icon-background: var(--color-accent-forest-soft); --topic-icon-color: var(--color-accent-forest); } @@ -51,7 +52,8 @@ img { :host([data-icon-key='priority']), :host([data-icon-key='set']), :host([data-icon-key='equality']), -:host([data-icon-key='ordering']) { +:host([data-icon-key='ordering']), +:host([data-icon-key='validation']) { --topic-icon-background: var(--color-accent-indigo-soft); --topic-icon-color: var(--color-accent-indigo); } diff --git a/tools/content/topic-icon-assets.spec.ts b/tools/content/topic-icon-assets.spec.ts new file mode 100644 index 0000000..44024aa --- /dev/null +++ b/tools/content/topic-icon-assets.spec.ts @@ -0,0 +1,15 @@ +import { readFile } from 'node:fs/promises'; +import { describe, expect, it } from 'vitest'; +import { TOPIC_ICON_KEYS } from '../../contracts/runtime-catalog.ts'; + +describe('Topic icon assets', () => { + it.each([...TOPIC_ICON_KEYS, 'generic'])('provides a local SVG for %s', async (iconKey) => { + const source = await readFile( + new URL(`../../public/icons/topics/${iconKey}.svg`, import.meta.url), + 'utf8', + ); + + expect(source).toMatch(/]*\bviewBox="0 0 24 24"/su); + expect(source).toContain(''); + }); +});