├── tea-service ├── tea-api │ ├── build.gradle │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── tea │ │ │ └── api │ │ │ ├── Water.java │ │ │ ├── Tealeaf.java │ │ │ └── TeaResponse.java │ └── gradle.lockfile ├── src │ ├── main │ │ ├── resources │ │ │ ├── public │ │ │ │ ├── assets │ │ │ │ │ ├── favicon.ico │ │ │ │ │ ├── observations.js │ │ │ │ │ └── steep.js │ │ │ │ └── observations.html │ │ │ ├── build.properties │ │ │ ├── logback-access.xml │ │ │ ├── logback-spring.xml │ │ │ ├── application.properties │ │ │ └── templates │ │ │ │ └── steep.html │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── tea │ │ │ ├── config │ │ │ ├── FeignClientConfig.java │ │ │ ├── LogBookConfig.java │ │ │ └── ActuatorConfig.java │ │ │ ├── service │ │ │ ├── MakeTeaConvention.java │ │ │ ├── TeaService.java │ │ │ ├── MakeTeaContext.java │ │ │ ├── DefaultMakeTeaConvention.java │ │ │ ├── MakeTeaDocumentation.java │ │ │ ├── ObservedTeaService.java │ │ │ └── DefaultTeaService.java │ │ │ ├── controller │ │ │ ├── HomeController.java │ │ │ ├── SteepController.java │ │ │ ├── SseController.java │ │ │ └── TeaController.java │ │ │ ├── water │ │ │ └── WaterClient.java │ │ │ ├── tealeaf │ │ │ └── TealeafClient.java │ │ │ ├── FrenchHornDemo.java │ │ │ ├── observation │ │ │ ├── BassObservationHandler.java │ │ │ ├── PercussionObservationHandler.java │ │ │ ├── SseObservationHandler.java │ │ │ └── MelodyObservationHandler.java │ │ │ └── TeaServiceApplication.java │ └── test │ │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── tea │ │ └── TeaServiceApplicationTest.java ├── docs │ └── index.adoc └── build.gradle ├── .gitattributes ├── gradle.properties ├── docker ├── mysql │ └── initdb │ │ └── init.sql ├── grafana │ ├── grafana.ini │ ├── provisioning │ │ ├── dashboards │ │ │ └── dashboard.yml │ │ ├── datasources │ │ │ └── datasource.yml │ │ └── alerting │ │ │ └── alerts.yml │ ├── README.md │ └── tempo.yml ├── toxiproxy │ └── toxiproxy.json └── prometheus │ └── prometheus.yml ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── dependency-locking.gradle ├── idea.gradle └── spring-boot.gradle ├── water-service ├── water-api │ ├── build.gradle │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── water │ │ │ └── api │ │ │ ├── WaterModel.java │ │ │ ├── SimpleWaterModel.java │ │ │ └── CreateWaterRequest.java │ └── gradle.lockfile ├── src │ ├── test │ │ ├── resources │ │ │ └── application-test.properties │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── water │ │ │ └── WaterServiceApplicationTest.java │ └── main │ │ ├── resources │ │ ├── build.properties │ │ ├── db │ │ │ ├── migration │ │ │ │ ├── V1_1__insert_water_resources.sql │ │ │ │ └── V1__create_water_table.sql │ │ │ └── mysql-migration │ │ │ │ ├── V1_1__insert_water_resources.sql │ │ │ │ └── V1__create_water_table.sql │ │ ├── application-mysql.properties │ │ ├── logback-access.xml │ │ ├── logback-spring.xml │ │ └── application.properties │ │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── water │ │ ├── repo │ │ ├── WaterRepository.java │ │ └── Water.java │ │ ├── controller │ │ ├── HomeController.java │ │ ├── RepresentationWaterModel.java │ │ ├── WaterModelAssembler.java │ │ └── WaterController.java │ │ ├── WaterServiceApplication.java │ │ └── observation │ │ └── PianoObservationHandler.java └── build.gradle ├── tealeaf-service ├── tealeaf-api │ ├── build.gradle │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── tealeaf │ │ │ └── api │ │ │ ├── TealeafModel.java │ │ │ ├── SimpleTealeafModel.java │ │ │ └── CreateTealeafRequest.java │ └── gradle.lockfile ├── src │ ├── test │ │ ├── resources │ │ │ └── application-test.properties │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── tealeaf │ │ │ └── TealeafServiceApplicationTest.java │ └── main │ │ ├── resources │ │ ├── build.properties │ │ ├── db │ │ │ ├── migration │ │ │ │ ├── V1_1__insert_tealeaf_resources.sql │ │ │ │ └── V1__create_tealeaf_table.sql │ │ │ └── mysql-migration │ │ │ │ ├── V1__create_tealeaf_table.sql │ │ │ │ └── V1_1__insert_tealeaf_resources.sql │ │ ├── application-mysql.properties │ │ ├── logback-access.xml │ │ ├── logback-spring.xml │ │ └── application.properties │ │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── tealeaf │ │ ├── controller │ │ ├── HomeController.java │ │ ├── RepresentationTealeafModel.java │ │ ├── TealeafModelAssembler.java │ │ └── TealeafController.java │ │ ├── repo │ │ ├── TealeafRepository.java │ │ └── Tealeaf.java │ │ └── TealeafServiceApplication.java └── build.gradle ├── lombok.config ├── .gitignore ├── eureka ├── build.gradle └── src │ ├── main │ ├── resources │ │ ├── build.properties │ │ ├── logback-spring.xml │ │ ├── application.properties │ │ └── logback-access.xml │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── eureka │ │ └── EurekaApplication.java │ └── test │ └── java │ └── org │ └── example │ └── teahouse │ └── eureka │ └── EurekaApplicationTest.java ├── spring-boot-admin ├── src │ ├── main │ │ ├── resources │ │ │ ├── build.properties │ │ │ ├── logback-spring.xml │ │ │ ├── application.properties │ │ │ └── logback-access.xml │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ └── teahouse │ │ │ └── sba │ │ │ └── SbaApplication.java │ └── test │ │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── sba │ │ └── SbaApplicationTest.java └── build.gradle ├── .editorconfig ├── load-gen ├── build.gradle ├── buildscript-gradle.lockfile └── src │ └── gatling │ ├── resources │ └── logback.xml │ └── java │ └── org │ └── example │ └── teahouse │ └── simulations │ └── steep │ └── SteepTeaSimulation.java ├── core ├── src │ └── main │ │ └── java │ │ └── org │ │ └── example │ │ └── teahouse │ │ └── core │ │ ├── error │ │ ├── ResourceNotFoundException.java │ │ └── CommonExceptionHandler.java │ │ ├── actuator │ │ ├── health │ │ │ ├── HealthClient.java │ │ │ ├── HealthResponse.java │ │ │ └── HealthClientAdapter.java │ │ ├── info │ │ │ └── RuntimeInfoContributor.java │ │ └── config │ │ │ └── CommonActuatorConfig.java │ │ ├── log │ │ └── access │ │ │ └── AccessLogConfig.java │ │ └── observation │ │ └── AbstractMidiObservationHandler.java ├── build.gradle └── gradle.lockfile ├── settings.gradle ├── .github └── workflows │ └── gradle.yml ├── Makefile ├── gradlew.bat ├── README.md ├── teahouse.postman_collection.json ├── docker-compose.yml └── gradlew /tea-service/tea-api/build.gradle: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.bat text eol=crlf 2 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.console=plain 2 | org.gradle.parallel=true 3 | -------------------------------------------------------------------------------- /docker/mysql/initdb/init.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE `water-db`; 2 | CREATE DATABASE `tealeaf-db`; 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonatan-ivanov/teahouse/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /water-service/water-api/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'jakarta.validation:jakarta.validation-api:3.+' 3 | } 4 | -------------------------------------------------------------------------------- /tealeaf-service/tealeaf-api/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'jakarta.validation:jakarta.validation-api:3.+' 3 | } 4 | -------------------------------------------------------------------------------- /water-service/src/test/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | # spring.output.ansi.enabled=never 2 | spring.flyway.clean-disabled=false 3 | -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | config.stopBubbling=true 2 | lombok.addLombokGeneratedAnnotation=true 3 | lombok.anyConstructor.addConstructorProperties=true 4 | -------------------------------------------------------------------------------- /tealeaf-service/src/test/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | # spring.output.ansi.enabled=never 2 | spring.flyway.clean-disabled=false 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | 4 | .idea/ 5 | out/ 6 | *.iws 7 | *.iml 8 | *.ipr 9 | .vscode/ 10 | 11 | tea-service/docs/index.html 12 | 13 | logs/ 14 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/public/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jonatan-ivanov/teahouse/HEAD/tea-service/src/main/resources/public/assets/favicon.ico -------------------------------------------------------------------------------- /eureka/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: "$rootDir/gradle/spring-boot.gradle" 2 | 3 | dependencies { 4 | implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' 5 | } 6 | -------------------------------------------------------------------------------- /eureka/src/main/resources/build.properties: -------------------------------------------------------------------------------- 1 | info.buildTool.sourceCompatibility=${java.sourceCompatibility} 2 | info.buildTool.targetCompatibility=${java.targetCompatibility} 3 | info.buildTool.gradleVersion=${gradle.gradleVersion} 4 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/build.properties: -------------------------------------------------------------------------------- 1 | info.buildTool.sourceCompatibility=${java.sourceCompatibility} 2 | info.buildTool.targetCompatibility=${java.targetCompatibility} 3 | info.buildTool.gradleVersion=${gradle.gradleVersion} 4 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/build.properties: -------------------------------------------------------------------------------- 1 | info.buildTool.sourceCompatibility=${java.sourceCompatibility} 2 | info.buildTool.targetCompatibility=${java.targetCompatibility} 3 | info.buildTool.gradleVersion=${gradle.gradleVersion} 4 | -------------------------------------------------------------------------------- /water-service/src/main/resources/build.properties: -------------------------------------------------------------------------------- 1 | info.buildTool.sourceCompatibility=${java.sourceCompatibility} 2 | info.buildTool.targetCompatibility=${java.targetCompatibility} 3 | info.buildTool.gradleVersion=${gradle.gradleVersion} 4 | -------------------------------------------------------------------------------- /spring-boot-admin/src/main/resources/build.properties: -------------------------------------------------------------------------------- 1 | info.buildTool.sourceCompatibility=${java.sourceCompatibility} 2 | info.buildTool.targetCompatibility=${java.targetCompatibility} 3 | info.buildTool.gradleVersion=${gradle.gradleVersion} 4 | -------------------------------------------------------------------------------- /docker/grafana/grafana.ini: -------------------------------------------------------------------------------- 1 | [feature_toggles] 2 | enable = tempoSearch tempoBackendSearch tempoApmTable traceToMetrics 3 | 4 | [users] 5 | default_theme = light 6 | 7 | [smtp] 8 | enabled = true 9 | host = host.docker.internal:25 10 | skip_verify = true 11 | -------------------------------------------------------------------------------- /spring-boot-admin/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: "$rootDir/gradle/spring-boot.gradle" 2 | 3 | dependencies { 4 | implementation 'de.codecentric:spring-boot-admin-starter-server:3.+' 5 | implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' 6 | } 7 | -------------------------------------------------------------------------------- /water-service/water-api/src/main/java/org/example/teahouse/water/api/WaterModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.api; 2 | 3 | import java.util.UUID; 4 | 5 | public interface WaterModel { 6 | UUID getId(); 7 | String getSize(); 8 | String getAmount(); 9 | } 10 | -------------------------------------------------------------------------------- /tea-service/docs/index.adoc: -------------------------------------------------------------------------------- 1 | = Observability features 2 | 3 | == Conventions 4 | 5 | include::../build/asciidoctor/_conventions.adoc[] 6 | 7 | == Metrics 8 | 9 | include::../build/asciidoctor/_metrics.adoc[] 10 | 11 | == Spans 12 | 13 | include::../build/asciidoctor/_spans.adoc[] 14 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /docker/grafana/provisioning/dashboards/dashboard.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | 3 | providers: 4 | - name: dashboards 5 | type: file 6 | disableDeletion: true 7 | editable: true 8 | options: 9 | path: /etc/grafana/provisioning/dashboards 10 | foldersFromFilesStructure: true 11 | -------------------------------------------------------------------------------- /water-service/src/main/resources/db/migration/V1_1__insert_water_resources.sql: -------------------------------------------------------------------------------- 1 | insert into water (id, amount, size) 2 | values 3 | ('dd1457d5-e0ec-4ba8-aaf5-b880e5aee672', '100 ml', 'small'), 4 | ('768805a0-3ef7-478f-8de4-6c3ed1bcf65b', '200 ml', 'medium'), 5 | ('71d27ee9-8146-411a-b87c-289aa198d881', '300 ml', 'large'); 6 | -------------------------------------------------------------------------------- /water-service/src/main/resources/db/mysql-migration/V1_1__insert_water_resources.sql: -------------------------------------------------------------------------------- 1 | insert into water (id, amount, size) 2 | values 3 | (unhex('dd1457d5e0ec4ba8aaf5b880e5aee672'), '100 ml', 'small'), 4 | (unhex('768805a03ef7478f8de46c3ed1bcf65b'), '200 ml', 'medium'), 5 | (unhex('71d27ee98146411ab87c289aa198d881'), '300 ml', 'large'); 6 | -------------------------------------------------------------------------------- /spring-boot-admin/src/test/java/org/example/teahouse/sba/SbaApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.sba; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest(classes = SbaApplication.class) 7 | class SbaApplicationTest { 8 | @Test void contextLoads() {} 9 | } 10 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | charset = utf-8 9 | indent_style = space 10 | indent_size = 4 11 | trim_trailing_whitespace = true 12 | 13 | [Makefile] 14 | indent_style = tab 15 | 16 | [*.md] 17 | trim_trailing_whitespace = false 18 | -------------------------------------------------------------------------------- /eureka/src/test/java/org/example/teahouse/eureka/EurekaApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.eureka; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest(classes = EurekaApplication.class) 7 | class EurekaApplicationTest { 8 | @Test void contextLoads() {} 9 | } 10 | -------------------------------------------------------------------------------- /tea-service/src/test/java/org/example/teahouse/tea/TeaServiceApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest(classes = TeaServiceApplication.class) 7 | class TeaServiceApplicationTest { 8 | @Test void contextLoads() {} 9 | } 10 | -------------------------------------------------------------------------------- /docker/toxiproxy/toxiproxy.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "water-db", 4 | "listen": "[::]:3307", 5 | "upstream": "host.docker.internal:3306", 6 | "enabled": true 7 | }, 8 | { 9 | "name": "tealeaf-db", 10 | "listen": "[::]:3308", 11 | "upstream": "host.docker.internal:3306", 12 | "enabled": true 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /tea-service/tea-api/src/main/java/org/example/teahouse/tea/api/Water.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.api; 2 | 3 | import lombok.Builder; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Value; 6 | 7 | @Value 8 | @Builder 9 | @RequiredArgsConstructor 10 | public class Water { 11 | private final String amount; 12 | private final String temperature; 13 | } 14 | -------------------------------------------------------------------------------- /load-gen/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | configurations.classpath { 3 | resolutionStrategy.activateDependencyLocking() 4 | } 5 | 6 | repositories { 7 | gradlePluginPortal() 8 | } 9 | dependencies { 10 | classpath 'gradle.plugin.io.gatling.gradle:gatling-gradle-plugin:3.+' 11 | } 12 | } 13 | 14 | apply plugin: 'java' 15 | apply plugin: 'io.gatling.gradle' 16 | -------------------------------------------------------------------------------- /water-service/src/main/resources/db/mysql-migration/V1__create_water_table.sql: -------------------------------------------------------------------------------- 1 | create table water ( 2 | id binary(16) not null, 3 | amount varchar(255) not null, 4 | size varchar(255) not null, 5 | primary key (id) 6 | ); 7 | 8 | alter table water add constraint UK_g79d6y6paax86h0g1xdlbh269 unique (amount); 9 | alter table water add constraint UK_ogxi7e4a41s1tp5bbrap35j2e unique (size); 10 | -------------------------------------------------------------------------------- /water-service/src/main/resources/db/migration/V1__create_water_table.sql: -------------------------------------------------------------------------------- 1 | create table water ( 2 | id uuid not null, 3 | amount varchar(255) not null, 4 | size varchar(255) not null, 5 | primary key (id) 6 | ); 7 | 8 | alter table if exists water add constraint UK_g79d6y6paax86h0g1xdlbh269 unique (amount); 9 | alter table if exists water add constraint UK_ogxi7e4a41s1tp5bbrap35j2e unique (size); 10 | -------------------------------------------------------------------------------- /tea-service/tea-api/src/main/java/org/example/teahouse/tea/api/Tealeaf.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.api; 2 | 3 | import lombok.Builder; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Value; 6 | 7 | @Value 8 | @Builder 9 | @RequiredArgsConstructor 10 | public class Tealeaf { 11 | private final String name; 12 | private final String type; 13 | private final String amount; 14 | } 15 | -------------------------------------------------------------------------------- /tealeaf-service/tealeaf-api/src/main/java/org/example/teahouse/tealeaf/api/TealeafModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.api; 2 | 3 | import java.util.UUID; 4 | 5 | public interface TealeafModel { 6 | UUID getId(); 7 | String getName(); 8 | String getType(); 9 | String getSuggestedAmount(); 10 | String getSuggestedWaterTemperature(); 11 | String getSuggestedSteepingTime(); 12 | } 13 | -------------------------------------------------------------------------------- /tea-service/tea-api/src/main/java/org/example/teahouse/tea/api/TeaResponse.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.api; 2 | 3 | import lombok.Builder; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Value; 6 | 7 | @Value 8 | @Builder 9 | @RequiredArgsConstructor 10 | public class TeaResponse { 11 | private final Water water; 12 | private final Tealeaf tealeaf; 13 | private final String steepingTime; 14 | } 15 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/config/FeignClientConfig.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.config; 2 | 3 | import feign.Logger; 4 | import feign.Logger.Level; 5 | 6 | import org.springframework.context.annotation.Bean; 7 | 8 | // @Configuration is intentionally omitted 9 | public class FeignClientConfig { 10 | @Bean 11 | Logger.Level feignLoggerLevel() { 12 | return Level.BASIC; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /docker/grafana/README.md: -------------------------------------------------------------------------------- 1 | The dashboards are originally from here: 2 | - [JVM (Micrometer)](https://grafana.com/grafana/dashboards/4701-jvm-micrometer/) 3 | - [Spring Boot 2.1 Statistics](https://grafana.com/grafana/dashboards/10280-microservices-spring-boot-2-1/) 4 | - [Spring Boot HikariCP / JDBC](https://grafana.com/grafana/dashboards/6083-spring-boot-hikaricp-jdbc/) 5 | - [Prometheus Stats](https://grafana.com/grafana/dashboards/2-prometheus-stats/) 6 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/error/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.error; 2 | 3 | public class ResourceNotFoundException extends RuntimeException { 4 | 5 | private final String name; 6 | 7 | public ResourceNotFoundException(String name) { 8 | super("Resource not found: " + name); 9 | this.name = name; 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/db/migration/V1_1__insert_tealeaf_resources.sql: -------------------------------------------------------------------------------- 1 | insert into tealeaf (id, name, suggested_amount, suggested_steeping_time, suggested_water_temperature, type) 2 | values 3 | ('6b55663a-1b50-43f1-a3b3-40939e89c4ad', 'sencha', '3 g', '3 min', '75 °C', 'green'), 4 | ('b00a63a4-9796-4c82-8dd0-5654e872dcf2', 'gyokuro', '2 g', '2 min', '70 °C', 'green'), 5 | ('98928e21-922f-4bd0-b5e5-275a4328cf7f', 'da hong pao', '5 g', '3 min', '99 °C', 'black'); 6 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.gradle.toolchains.foojay-resolver-convention' version '1.+' 3 | } 4 | 5 | rootProject.name = 'teahouse' 6 | 7 | include ':core' 8 | 9 | include ':eureka' 10 | include ':spring-boot-admin' 11 | 12 | include ':water-service' 13 | include ':water-service:water-api' 14 | 15 | include ':tealeaf-service' 16 | include ':tealeaf-service:tealeaf-api' 17 | 18 | include ':tea-service' 19 | include ':tea-service:tea-api' 20 | 21 | include ':load-gen' 22 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/db/migration/V1__create_tealeaf_table.sql: -------------------------------------------------------------------------------- 1 | create table tealeaf ( 2 | id uuid not null, 3 | name varchar(255) not null, 4 | suggested_amount varchar(255) not null, 5 | suggested_steeping_time varchar(255) not null, 6 | suggested_water_temperature varchar(255) not null, 7 | type varchar(255) not null, 8 | primary key (id) 9 | ); 10 | 11 | alter table if exists tealeaf add constraint UK_9v6fqg4d3pq6ryc2xghqq0sqj unique (name); 12 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/db/mysql-migration/V1__create_tealeaf_table.sql: -------------------------------------------------------------------------------- 1 | create table tealeaf ( 2 | id binary(16) not null, 3 | name varchar(255) not null, 4 | suggested_amount varchar(255) not null, 5 | suggested_steeping_time varchar(255) not null, 6 | suggested_water_temperature varchar(255) not null, 7 | type varchar(255) not null, 8 | primary key (id) 9 | ); 10 | 11 | alter table tealeaf add constraint UK_9v6fqg4d3pq6ryc2xghqq0sqj unique (name); 12 | -------------------------------------------------------------------------------- /water-service/water-api/src/main/java/org/example/teahouse/water/api/SimpleWaterModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.api; 2 | 3 | import java.util.UUID; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @Builder 10 | @RequiredArgsConstructor 11 | public class SimpleWaterModel implements WaterModel { 12 | private final UUID id; 13 | private final String size; 14 | private final String amount; 15 | } 16 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/db/mysql-migration/V1_1__insert_tealeaf_resources.sql: -------------------------------------------------------------------------------- 1 | insert into tealeaf (id, name, suggested_amount, suggested_steeping_time, suggested_water_temperature, type) 2 | values 3 | (unhex('6b55663a1b5043f1a3b340939e89c4ad'), 'sencha', '3 g', '3 min', '75 °C', 'green'), 4 | (unhex('b00a63a497964c828dd05654e872dcf2'), 'gyokuro', '2 g', '2 min', '70 °C', 'green'), 5 | (unhex('98928e21922f4bd0b5e5275a4328cf7f'), 'da hong pao', '5 g', '3 min', '99 °C', 'black'); 6 | -------------------------------------------------------------------------------- /gradle/dependency-locking.gradle: -------------------------------------------------------------------------------- 1 | dependencyLocking { 2 | lockAllConfigurations() 3 | } 4 | 5 | task resolveAndLockAll { // ./gradlew resolveAndLockAll --write-locks 6 | description = 'Resolves dependencies of all configurations and writes them into the lock file.' 7 | doFirst { 8 | assert gradle.startParameter.writeDependencyLocks : 'Execute resolveAndLockAll --write-locks' 9 | } 10 | doLast { 11 | configurations.findAll { it.canBeResolved }.each { it.resolve() } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/MakeTeaConvention.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import io.micrometer.common.lang.NonNull; 4 | import io.micrometer.observation.Observation; 5 | import io.micrometer.observation.ObservationConvention; 6 | 7 | public interface MakeTeaConvention extends ObservationConvention { 8 | @Override 9 | default boolean supportsContext(@NonNull Observation.Context context) { 10 | return context instanceof MakeTeaContext; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/TeaService.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import java.util.Collection; 4 | 5 | import org.example.teahouse.tea.api.TeaResponse; 6 | import org.example.teahouse.tealeaf.api.SimpleTealeafModel; 7 | import org.example.teahouse.water.api.SimpleWaterModel; 8 | 9 | public interface TeaService { 10 | TeaResponse make(String name, String size); 11 | 12 | Collection tealeaves(); 13 | 14 | Collection waters(); 15 | } 16 | -------------------------------------------------------------------------------- /docker/prometheus/prometheus.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 10s 3 | evaluation_interval: 10s 4 | 5 | scrape_configs: 6 | - job_name: 'prometheus' 7 | static_configs: 8 | - targets: ['host.docker.internal:9090'] 9 | - job_name: 'eureka' 10 | # scheme: 'https' 11 | metrics_path: '/actuator/prometheus' 12 | eureka_sd_configs: 13 | - server: http://host.docker.internal:8761/eureka 14 | - job_name: 'tempo' 15 | static_configs: 16 | - targets: ['host.docker.internal:3200'] 17 | -------------------------------------------------------------------------------- /water-service/src/main/resources/application-mysql.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://localhost:3307/water-db 2 | spring.datasource.username=root 3 | spring.datasource.password=password 4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 5 | 6 | spring.flyway.locations=classpath:db/mysql-migration 7 | 8 | # this disables HikariCP but it lets us inject tail latency on the TCP level via toxiproxy (a new connection is needed to inject latency) 9 | #spring.datasource.type=org.springframework.jdbc.datasource.SimpleDriverDataSource 10 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/application-mysql.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://localhost:3308/tealeaf-db 2 | spring.datasource.username=root 3 | spring.datasource.password=password 4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 5 | 6 | spring.flyway.locations=classpath:db/mysql-migration 7 | 8 | # this disables HikariCP but it lets us inject tail latency on the TCP level via toxiproxy (a new connection is needed to inject latency) 9 | #spring.datasource.type=org.springframework.jdbc.datasource.SimpleDriverDataSource 10 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/controller/HomeController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.controller; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.servlet.view.RedirectView; 8 | 9 | @Hidden 10 | @Controller 11 | public class HomeController { 12 | @GetMapping("/") 13 | RedirectView redirectToSwaggerUi() { 14 | return new RedirectView("/swagger-ui.html"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/repo/WaterRepository.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.repo; 2 | 3 | import java.util.Optional; 4 | import java.util.UUID; 5 | 6 | import org.springframework.data.repository.CrudRepository; 7 | import org.springframework.data.repository.PagingAndSortingRepository; 8 | import org.springframework.data.repository.query.Param; 9 | 10 | public interface WaterRepository extends PagingAndSortingRepository, CrudRepository { 11 | Optional findBySize(@Param("size") String size); 12 | } 13 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/controller/HomeController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.controller; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.servlet.view.RedirectView; 8 | 9 | @Hidden 10 | @Controller 11 | public class HomeController { 12 | @GetMapping("/") 13 | RedirectView redirectToSwaggerUi() { 14 | return new RedirectView("/swagger-ui.html"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/controller/HomeController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.controller; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.servlet.view.RedirectView; 8 | 9 | @Hidden 10 | @Controller 11 | public class HomeController { 12 | @GetMapping("/") 13 | RedirectView redirectToSwaggerUi() { 14 | return new RedirectView("/swagger-ui.html"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/repo/TealeafRepository.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.repo; 2 | 3 | import java.util.Optional; 4 | import java.util.UUID; 5 | 6 | import org.springframework.data.repository.CrudRepository; 7 | import org.springframework.data.repository.PagingAndSortingRepository; 8 | import org.springframework.data.repository.query.Param; 9 | 10 | public interface TealeafRepository extends PagingAndSortingRepository, CrudRepository { 11 | Optional findByName(@Param("name") String name); 12 | } 13 | -------------------------------------------------------------------------------- /water-service/water-api/src/main/java/org/example/teahouse/water/api/CreateWaterRequest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.api; 2 | 3 | import jakarta.validation.constraints.NotNull; 4 | import jakarta.validation.constraints.Size; 5 | import lombok.Builder; 6 | import lombok.RequiredArgsConstructor; 7 | import lombok.Value; 8 | 9 | @Value 10 | @Builder 11 | @RequiredArgsConstructor 12 | public class CreateWaterRequest { 13 | @NotNull 14 | @Size(min = 1, max = 10) 15 | private final String size; 16 | 17 | @NotNull 18 | @Size(min = 1, max = 10) 19 | private final String amount; 20 | } 21 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/MakeTeaContext.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import io.micrometer.observation.Observation; 4 | 5 | public class MakeTeaContext extends Observation.Context { 6 | private final String teaName; 7 | private final String waterSize; 8 | 9 | MakeTeaContext(String teaName, String waterSize) { 10 | this.teaName = teaName; 11 | this.waterSize = waterSize; 12 | } 13 | 14 | String getTeaName() { 15 | return teaName; 16 | } 17 | 18 | String getWaterSize() { 19 | return waterSize; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tealeaf-service/tealeaf-api/src/main/java/org/example/teahouse/tealeaf/api/SimpleTealeafModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.api; 2 | 3 | import java.util.UUID; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @Builder 10 | @RequiredArgsConstructor 11 | public class SimpleTealeafModel implements TealeafModel{ 12 | private final UUID id; 13 | private final String name; 14 | private final String type; 15 | private final String suggestedAmount; 16 | private final String suggestedWaterTemperature; 17 | private final String suggestedSteepingTime; 18 | } 19 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/config/LogBookConfig.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.config; 2 | 3 | import okhttp3.OkHttpClient; 4 | import org.zalando.logbook.Logbook; 5 | import org.zalando.logbook.okhttp.LogbookInterceptor; 6 | 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class LogBookConfig { 12 | @Bean 13 | public OkHttpClient.Builder okHttpClientBuilder(Logbook logbook) { 14 | return new OkHttpClient.Builder() 15 | .addNetworkInterceptor(new LogbookInterceptor(logbook)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/actuator/health/HealthClient.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.actuator.health; 2 | 3 | import org.springframework.boot.actuate.health.HealthIndicator; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | /** 7 | * Only single-level inheritance supported by Feign and {@link HealthIndicator} extends {@link org.springframework.boot.actuate.health.HealthContributor} 8 | * so returning a Health instance won't work. 9 | * Also, {@link org.springframework.boot.actuate.health.Health} is not deserializable, see {@link HealthResponse}. 10 | */ 11 | public interface HealthClient { 12 | @GetMapping("/actuator/health") 13 | HealthResponse health(); 14 | } 15 | -------------------------------------------------------------------------------- /docker/grafana/tempo.yml: -------------------------------------------------------------------------------- 1 | server: 2 | http_listen_port: 3200 3 | distributor: 4 | receivers: 5 | zipkin: 6 | endpoint: "tempo:9411" 7 | storage: 8 | trace: 9 | backend: local 10 | wal: 11 | path: /var/tempo/wal 12 | local: 13 | path: /var/tempo/blocks 14 | metrics_generator: 15 | registry: 16 | external_labels: 17 | source: tempo 18 | storage: 19 | path: /var/tempo/generator/wal 20 | remote_write: 21 | - url: http://host.docker.internal:9090/api/v1/write 22 | send_exemplars: true 23 | traces_storage: 24 | path: /var/tempo/generator/traces 25 | overrides: 26 | defaults: 27 | metrics_generator: 28 | processors: [service-graphs, span-metrics, local-blocks] 29 | -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'io.micrometer:micrometer-tracing' 3 | implementation 'org.springframework:spring-webmvc' 4 | implementation 'org.springframework.boot:spring-boot-actuator-autoconfigure' 5 | implementation 'com.google.guava:guava:33.+' 6 | implementation 'org.slf4j:slf4j-api' 7 | implementation 'org.apache.commons:commons-lang3' 8 | implementation 'io.github.openfeign:feign-micrometer' 9 | implementation('ch.qos.logback.access:logback-access-tomcat:2.+') { 10 | exclude group: 'org.apache.tomcat' 11 | exclude group: 'jakarta.servlet' 12 | } 13 | implementation 'org.apache.tomcat.embed:tomcat-embed-core' 14 | 15 | compileOnly 'net.ttddyy.observation:datasource-micrometer-spring-boot:1.+' 16 | } 17 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/controller/RepresentationWaterModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.controller; 2 | 3 | import java.util.UUID; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | import org.example.teahouse.water.api.WaterModel; 8 | import org.springframework.hateoas.RepresentationModel; 9 | import org.springframework.hateoas.server.core.Relation; 10 | 11 | @Getter 12 | @Builder 13 | @RequiredArgsConstructor 14 | @Relation(collectionRelation = "waters", itemRelation = "water") 15 | public class RepresentationWaterModel extends RepresentationModel implements WaterModel { 16 | private final UUID id; 17 | private final String size; 18 | private final String amount; 19 | } 20 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/public/assets/observations.js: -------------------------------------------------------------------------------- 1 | $(document).ready(() => { 2 | new EventSource('/sse').onmessage = onMessage; 3 | }); 4 | 5 | function onMessage(event) { 6 | $('#observation-container').append(createBadge(JSON.parse(event.data))); 7 | } 8 | 9 | function createBadge(observation) { 10 | console.log(observation); 11 | return $('') 12 | .addClass('badge my-1') 13 | .addClass(observation.error ? 'text-bg-danger' : 'text-bg-success') 14 | .addClass(getOpacity(observation.duration)) 15 | .append($('

').text(observation.duration)); 16 | } 17 | 18 | function getOpacity(duration) { 19 | if (duration <= 25) return 'opacity-50'; 20 | else if (duration < 100) return 'opacity-75'; 21 | else return 'opacity-100'; 22 | } 23 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/controller/SteepController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.controller; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | import lombok.RequiredArgsConstructor; 5 | import org.example.teahouse.tea.service.TeaService; 6 | 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.ui.Model; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | 11 | @Hidden 12 | @Controller 13 | @RequiredArgsConstructor 14 | public class SteepController { 15 | private final TeaService teaService; 16 | 17 | @GetMapping("/steep") 18 | public String steep(Model model) { 19 | model.addAttribute("tealeaves", teaService.tealeaves()); 20 | model.addAttribute("waters", teaService.waters()); 21 | 22 | return "steep"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/actuator/health/HealthResponse.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.actuator.health; 2 | 3 | import static java.util.stream.Collectors.toUnmodifiableMap; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import org.springframework.boot.actuate.health.Health; 8 | import org.springframework.boot.actuate.health.Status; 9 | 10 | public class HealthResponse extends HashMap { 11 | public Health toHealth() { 12 | Map details = this.entrySet().stream() 13 | .filter(entry -> !"status".equals(entry.getKey())) 14 | .collect(toUnmodifiableMap(Entry::getKey, Entry::getValue)); 15 | 16 | return Health 17 | .status(new Status(String.valueOf(this.get("status")))) 18 | .withDetails(details) 19 | .build(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tealeaf-service/tealeaf-api/src/main/java/org/example/teahouse/tealeaf/api/CreateTealeafRequest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.api; 2 | 3 | import jakarta.validation.constraints.NotNull; 4 | import jakarta.validation.constraints.Size; 5 | import lombok.Builder; 6 | import lombok.RequiredArgsConstructor; 7 | import lombok.Value; 8 | 9 | @Value 10 | @Builder 11 | @RequiredArgsConstructor 12 | public class CreateTealeafRequest { 13 | @NotNull 14 | @Size(min = 1, max = 30) 15 | private final String name; 16 | 17 | @NotNull 18 | @Size(min = 1, max = 10) 19 | private final String type; 20 | 21 | @NotNull 22 | @Size(min = 1, max = 10) 23 | private final String suggestedAmount; 24 | 25 | @NotNull 26 | @Size(min = 1, max = 10) 27 | private final String suggestedSteepingTime; 28 | 29 | @NotNull 30 | @Size(min = 1, max = 10) 31 | private final String suggestedWaterTemperature; 32 | } 33 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/water/WaterClient.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.water; 2 | 3 | import org.example.teahouse.core.actuator.health.HealthClient; 4 | import org.example.teahouse.tea.config.FeignClientConfig; 5 | import org.example.teahouse.water.api.SimpleWaterModel; 6 | import org.springframework.cloud.openfeign.FeignClient; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.hateoas.PagedModel; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestParam; 11 | 12 | @FeignClient(name = "water", configuration = FeignClientConfig.class) 13 | public interface WaterClient extends HealthClient { 14 | @GetMapping("/waters/search/findBySize") 15 | SimpleWaterModel findBySize(@RequestParam("size") String size); 16 | 17 | @GetMapping("/waters") 18 | PagedModel waters(Pageable pageable); 19 | } 20 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/WaterServiceApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.PropertySource; 8 | 9 | @SpringBootApplication 10 | @PropertySource("classpath:build.properties") 11 | @ComponentScan(basePackages = { "org.example.teahouse" }) 12 | public class WaterServiceApplication { 13 | public static void main(String[] args) { 14 | SpringApplication springApplication = new SpringApplication(WaterServiceApplication.class); 15 | springApplication.setApplicationStartup(new BufferingApplicationStartup(10_000)); 16 | springApplication.run(args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/TealeafServiceApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.PropertySource; 8 | 9 | @SpringBootApplication 10 | @PropertySource("classpath:build.properties") 11 | @ComponentScan(basePackages = { "org.example.teahouse" }) 12 | public class TealeafServiceApplication { 13 | public static void main(String[] args) { 14 | SpringApplication springApplication = new SpringApplication(TealeafServiceApplication.class); 15 | springApplication.setApplicationStartup(new BufferingApplicationStartup(10_000)); 16 | springApplication.run(args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/controller/RepresentationTealeafModel.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.controller; 2 | 3 | import java.util.UUID; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | import org.example.teahouse.tealeaf.api.TealeafModel; 8 | import org.springframework.hateoas.RepresentationModel; 9 | import org.springframework.hateoas.server.core.Relation; 10 | 11 | @Getter 12 | @Builder 13 | @RequiredArgsConstructor 14 | @Relation(collectionRelation = "tealeaves", itemRelation = "tealeaf") 15 | public class RepresentationTealeafModel extends RepresentationModel implements TealeafModel { 16 | private final UUID id; 17 | private final String name; 18 | private final String type; 19 | private final String suggestedAmount; 20 | private final String suggestedWaterTemperature; 21 | private final String suggestedSteepingTime; 22 | } 23 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/tealeaf/TealeafClient.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.tealeaf; 2 | 3 | import org.example.teahouse.core.actuator.health.HealthClient; 4 | import org.example.teahouse.tea.config.FeignClientConfig; 5 | import org.example.teahouse.tealeaf.api.SimpleTealeafModel; 6 | import org.springframework.cloud.openfeign.FeignClient; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.hateoas.PagedModel; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestParam; 11 | 12 | @FeignClient(name = "tealeaf", configuration = FeignClientConfig.class) 13 | public interface TealeafClient extends HealthClient { 14 | @GetMapping("/tealeaves/search/findByName") 15 | SimpleTealeafModel findByName(@RequestParam("name") String name); 16 | 17 | @GetMapping("/tealeaves") 18 | PagedModel tealeaves(Pageable pageable); 19 | } 20 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/actuator/health/HealthClientAdapter.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.actuator.health; 2 | 3 | import java.util.Optional; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.boot.actuate.health.Health; 6 | import org.springframework.boot.actuate.health.HealthIndicator; 7 | 8 | @RequiredArgsConstructor 9 | public class HealthClientAdapter implements HealthIndicator { 10 | private final HealthClient healthClient; 11 | 12 | @Override 13 | public Health health() { 14 | try { 15 | return Optional.ofNullable(healthClient.health()) 16 | .map(HealthResponse::toHealth) 17 | .orElse(Health.down() 18 | .withDetail("error", "null response") 19 | .build() 20 | ); 21 | } 22 | catch (Exception exception) { 23 | return Health.down(exception).build(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /load-gen/buildscript-gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | com.fasterxml.jackson.core:jackson-annotations:2.20=classpath 5 | com.fasterxml.jackson.core:jackson-core:2.20.0=classpath 6 | com.fasterxml.jackson.core:jackson-databind:2.20.0=classpath 7 | com.fasterxml.jackson:jackson-bom:2.20.0=classpath 8 | com.github.spotbugs:spotbugs-annotations:4.9.0=classpath 9 | com.google.code.findbugs:jsr305:3.0.2=classpath 10 | com.typesafe:config:1.4.5=classpath 11 | gradle.plugin.io.gatling.gradle:gatling-gradle-plugin:3.14.9=classpath 12 | io.gatling:gatling-asm-shaded:9.9.0=classpath 13 | io.gatling:gatling-enterprise-plugin-commons:1.20.7=classpath 14 | io.gatling:gatling-scanner:1.6.6=classpath 15 | io.gatling:gatling-shared-cli:0.0.6=classpath 16 | org.codehaus.plexus:plexus-utils:4.0.2=classpath 17 | org.jspecify:jspecify:1.0.0=classpath 18 | empty= 19 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/FrenchHornDemo.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea; 2 | 3 | import javax.sound.midi.MidiChannel; 4 | import javax.sound.midi.MidiSystem; 5 | import javax.sound.midi.MidiUnavailableException; 6 | import javax.sound.midi.Synthesizer; 7 | 8 | public class FrenchHornDemo { 9 | public static void main(String[] args) throws MidiUnavailableException, InterruptedException { 10 | Synthesizer synthesizer = MidiSystem.getSynthesizer(); 11 | synthesizer.open(); 12 | MidiChannel channel = synthesizer.getChannels()[0]; 13 | // French Horn is bank #0 preset #60 14 | channel.programChange(synthesizer.getAvailableInstruments()[60].getPatch().getProgram()); 15 | 16 | // C4 (middle C) 17 | int note = 60; 18 | try { 19 | channel.noteOn(note, 90); 20 | Thread.sleep(1_000); 21 | } 22 | finally { 23 | channel.noteOff(note); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /load-gen/src/gatling/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | %d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx 10 | 11 | false 12 | 13 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/DefaultMakeTeaConvention.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import io.micrometer.common.KeyValues; 4 | import io.micrometer.common.lang.NonNull; 5 | import io.micrometer.common.lang.Nullable; 6 | 7 | public class DefaultMakeTeaConvention implements MakeTeaConvention { 8 | 9 | @Nullable 10 | @Override 11 | public String getName() { 12 | return "make.tea"; 13 | } 14 | 15 | @NonNull 16 | @Override 17 | public KeyValues getLowCardinalityKeyValues(MakeTeaContext context) { 18 | // return KeyValues.of( 19 | // "tea.name", context.getTeaName(), 20 | // "water.size", context.getWaterSize() 21 | // ); 22 | 23 | // with "MakeTeaDocumentation" 24 | return KeyValues.of( 25 | MakeTeaDocumentation.LowCardinalityKeyNames.TEA_LEAF_NAME.withValue(context.getTeaName()), 26 | MakeTeaDocumentation.LowCardinalityKeyNames.WATER_SIZE.withValue(context.getWaterSize()) 27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-admin/src/main/java/org/example/teahouse/sba/SbaApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.sba; 2 | 3 | import de.codecentric.boot.admin.server.config.EnableAdminServer; 4 | import org.example.teahouse.core.actuator.config.CommonActuatorConfig; 5 | 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; 9 | import org.springframework.context.annotation.Import; 10 | import org.springframework.context.annotation.PropertySource; 11 | 12 | @EnableAdminServer 13 | @SpringBootApplication 14 | @PropertySource("classpath:build.properties") 15 | @Import({CommonActuatorConfig.class}) 16 | public class SbaApplication { 17 | public static void main(String[] args) { 18 | SpringApplication springApplication = new SpringApplication(SbaApplication.class); 19 | springApplication.setApplicationStartup(new BufferingApplicationStartup(10_000)); 20 | springApplication.run(args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /eureka/src/main/java/org/example/teahouse/eureka/EurekaApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.eureka; 2 | 3 | import org.example.teahouse.core.actuator.config.CommonActuatorConfig; 4 | 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; 8 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 9 | import org.springframework.context.annotation.Import; 10 | import org.springframework.context.annotation.PropertySource; 11 | 12 | @EnableEurekaServer 13 | @SpringBootApplication 14 | @PropertySource("classpath:build.properties") 15 | @Import({CommonActuatorConfig.class}) 16 | public class EurekaApplication { 17 | public static void main(String[] args) { 18 | SpringApplication springApplication = new SpringApplication(EurekaApplication.class); 19 | springApplication.setApplicationStartup(new BufferingApplicationStartup(10_000)); 20 | springApplication.run(args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/log/access/AccessLogConfig.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.log.access; 2 | 3 | import ch.qos.logback.access.tomcat.LogbackValve; 4 | import org.apache.catalina.Context; 5 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 6 | import org.springframework.boot.web.server.WebServerFactoryCustomizer; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class AccessLogConfig { 12 | 13 | @Bean 14 | public WebServerFactoryCustomizer webServerFactoryCustomizer() { 15 | return factory -> factory.addContextCustomizers(this::tomcatContextCustomizer); 16 | } 17 | 18 | private void tomcatContextCustomizer(Context context) { 19 | LogbackValve logbackValve = new LogbackValve(); 20 | logbackValve.setAsyncSupported(true); 21 | logbackValve.setFilename("logback-access.xml"); 22 | context.getPipeline().addValve(logbackValve); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | branches: [ main ] 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | if: ${{ github.repository_owner == 'jonatan-ivanov' }} 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v4 19 | - name: Setup Java 20 | uses: actions/setup-java@v4 21 | with: 22 | distribution: 'liberica' 23 | java-version: 25 24 | cache: 'gradle' 25 | check-latest: true 26 | - name: Setup Gradle 27 | uses: gradle/actions/setup-gradle@v4 28 | - name: Build Info 29 | shell: bash 30 | run: | 31 | echo 'Triggered by: ${{ github.event_name }}' 32 | echo 'Ref type: ${{ github.ref_type }}' 33 | echo 'Ref name: ${{ github.ref_name }}' 34 | echo 'Ref: ${{ github.ref }}' 35 | echo 'Commit: ${{ github.sha }}' 36 | ./gradlew --version 37 | - name: Build with Gradle 38 | shell: bash 39 | run: ./gradlew build 40 | -------------------------------------------------------------------------------- /eureka/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ${FILE_LOG_PATTERN} 10 | 11 | ${payloadFileName} 12 | 13 | ${payloadFileName}.%i 14 | 15 | 16 | 10MB 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /spring-boot-admin/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ${FILE_LOG_PATTERN} 10 | 11 | ${payloadFileName} 12 | 13 | ${payloadFileName}.%i 14 | 15 | 16 | 10MB 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/public/observations.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Observations 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |

What is going on!?

14 |
15 |
16 |
17 |
18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /water-service/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: "$rootDir/gradle/spring-boot.gradle" 2 | 3 | dependencies { 4 | implementation project(':water-service:water-api') 5 | 6 | implementation 'org.springframework.boot:spring-boot-starter-hateoas' 7 | implementation 'org.springframework.boot:spring-boot-starter-validation' 8 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 9 | implementation 'org.springframework.boot:spring-boot-starter-data-rest' 10 | implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' 11 | implementation 'io.micrometer:micrometer-tracing-bridge-brave' 12 | implementation 'io.zipkin.reporter2:zipkin-reporter-brave' 13 | 14 | implementation 'net.ttddyy.observation:datasource-micrometer-spring-boot:1.+' 15 | 16 | implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.+' 17 | 18 | implementation 'org.zalando:logbook-spring-boot-starter:3.+' 19 | 20 | runtimeOnly 'com.github.loki4j:loki-logback-appender:1.+' 21 | 22 | runtimeOnly 'com.h2database:h2' 23 | runtimeOnly 'mysql:mysql-connector-java:8.+' 24 | runtimeOnly 'org.flywaydb:flyway-core' 25 | runtimeOnly 'org.flywaydb:flyway-mysql' 26 | 27 | testImplementation 'org.flywaydb:flyway-core' 28 | } 29 | -------------------------------------------------------------------------------- /tealeaf-service/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: "$rootDir/gradle/spring-boot.gradle" 2 | 3 | dependencies { 4 | implementation project(':tealeaf-service:tealeaf-api') 5 | 6 | implementation 'org.springframework.boot:spring-boot-starter-hateoas' 7 | implementation 'org.springframework.boot:spring-boot-starter-validation' 8 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 9 | implementation 'org.springframework.boot:spring-boot-starter-data-rest' 10 | implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' 11 | implementation 'io.micrometer:micrometer-tracing-bridge-brave' 12 | implementation 'io.zipkin.reporter2:zipkin-reporter-brave' 13 | 14 | implementation 'net.ttddyy.observation:datasource-micrometer-spring-boot:1.+' 15 | 16 | implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.+' 17 | 18 | implementation 'org.zalando:logbook-spring-boot-starter:3.+' 19 | 20 | runtimeOnly 'com.github.loki4j:loki-logback-appender:1.+' 21 | 22 | runtimeOnly 'com.h2database:h2' 23 | runtimeOnly 'mysql:mysql-connector-java:8.+' 24 | runtimeOnly 'org.flywaydb:flyway-core' 25 | runtimeOnly 'org.flywaydb:flyway-mysql' 26 | 27 | testImplementation 'org.flywaydb:flyway-core' 28 | } 29 | -------------------------------------------------------------------------------- /gradle/idea.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | apply plugin: 'idea' 3 | 4 | idea { 5 | module { 6 | downloadJavadoc = true 7 | downloadSources = true 8 | 9 | iml.withXml { // Spring Facet 10 | def moduleRoot = it.asNode() 11 | def facetManager = moduleRoot.component.find { component -> component.'@name' == 'FacetManager' } 12 | if (!facetManager) { 13 | facetManager = moduleRoot.appendNode('component', [name: 'FacetManager']) 14 | } 15 | def springFacet = facetManager.facet.find { facet -> facet.'@type' == 'Spring' && facet.'@name' == 'Spring' } 16 | if (!springFacet) { 17 | springFacet = facetManager.appendNode('facet', [type: 'Spring', name: 'Spring']) 18 | springFacet.appendNode('configuration') 19 | } 20 | } 21 | } 22 | } 23 | } 24 | 25 | idea { 26 | // Enable annotation processing (e.g.: for Lombok) 27 | project.ipr.withXml { provider -> 28 | provider.node.component 29 | .find { it.@name == 'CompilerConfiguration' } 30 | .annotationProcessing.replaceNode { annotationProcessing {profile(default: true, name: 'Default', enabled: true) } } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /eureka/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=eureka 2 | spring.application.org=teahouse 3 | spring.profiles.default=local 4 | server.port=8761 5 | 6 | spring.output.ansi.enabled=always 7 | spring.jackson.serialization.indent_output=true 8 | spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat 9 | 10 | spring.mvc.problemdetails.enabled=true 11 | 12 | logging.file.name=${spring.application.home:.}/logs/${spring.application.name}.log 13 | management.endpoints.web.exposure.include=* 14 | management.endpoint.health.show-details=always 15 | management.endpoint.env.show-values=always 16 | management.info.env.enabled=true 17 | management.info.java.enabled=true 18 | management.info.os.enabled=true 19 | management.info.process.enabled=true 20 | 21 | spring.cloud.discovery.client.composite-indicator.enabled=false 22 | 23 | management.observations.key-values.org=${spring.application.org} 24 | management.metrics.tags.application=${spring.application.name} 25 | management.metrics.tags.org=${spring.application.org} 26 | management.metrics.tags.profiles=${spring.profiles.active} 27 | management.prometheus.metrics.export.step=10s 28 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 29 | management.tracing.sampling.probability=1.0 30 | 31 | server.tomcat.mbeanregistry.enabled=true 32 | -------------------------------------------------------------------------------- /spring-boot-admin/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=spring-boot-admin 2 | spring.application.org=teahouse 3 | spring.profiles.default=local 4 | server.port=8080 5 | 6 | spring.output.ansi.enabled=always 7 | spring.jackson.serialization.indent_output=true 8 | spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat 9 | 10 | spring.mvc.problemdetails.enabled=true 11 | 12 | logging.file.name=${spring.application.home:.}/logs/${spring.application.name}.log 13 | management.endpoints.web.exposure.include=* 14 | management.endpoint.health.show-details=always 15 | management.endpoint.env.show-values=always 16 | management.info.env.enabled=true 17 | management.info.java.enabled=true 18 | management.info.os.enabled=true 19 | management.info.process.enabled=true 20 | 21 | spring.cloud.discovery.client.composite-indicator.enabled=false 22 | 23 | management.observations.key-values.org=${spring.application.org} 24 | management.metrics.tags.application=${spring.application.name} 25 | management.metrics.tags.org=${spring.application.org} 26 | management.metrics.tags.profiles=${spring.profiles.active} 27 | management.prometheus.metrics.export.step=10s 28 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 29 | management.tracing.sampling.probability=1.0 30 | 31 | server.tomcat.mbeanregistry.enabled=true 32 | 33 | logging.level.com.netflix.discovery=OFF 34 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/controller/SseController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.controller; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import org.example.teahouse.tea.observation.SseObservationHandler; 6 | 7 | import org.springframework.http.MediaType; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; 11 | 12 | @Controller 13 | public class SseController { 14 | private final SseObservationHandler sseObservationHandler; 15 | 16 | SseController(SseObservationHandler sseObservationHandler) { 17 | this.sseObservationHandler = sseObservationHandler; 18 | } 19 | 20 | @GetMapping(path="/sse", produces=MediaType.TEXT_EVENT_STREAM_VALUE) 21 | SseEmitter sse() { 22 | SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE); 23 | CompletableFuture.runAsync(() -> emit(sseEmitter)); 24 | return sseEmitter; 25 | } 26 | 27 | @SuppressWarnings({"InfiniteLoopStatement"}) 28 | private void emit(SseEmitter sseEmitter) { 29 | try { 30 | while (true) { 31 | sseEmitter.send(sseObservationHandler.take()); 32 | } 33 | } 34 | catch (Exception e) { 35 | sseEmitter.completeWithError(e); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/controller/TeaController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.controller; 2 | 3 | import io.micrometer.core.instrument.Counter; 4 | import io.micrometer.core.instrument.MeterRegistry; 5 | import io.swagger.v3.oas.annotations.Operation; 6 | import io.swagger.v3.oas.annotations.tags.Tag; 7 | import lombok.RequiredArgsConstructor; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.example.teahouse.tea.api.TeaResponse; 10 | import org.example.teahouse.tea.service.TeaService; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestParam; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | @Slf4j 17 | @RestController 18 | @RequiredArgsConstructor 19 | @Tag(name = "Tea API") 20 | public class TeaController { 21 | private final TeaService teaService; 22 | private final MeterRegistry registry; 23 | 24 | @GetMapping("/tea/{name}") 25 | @Operation(summary = "Tells you how to make a cup of tea") 26 | public TeaResponse make(@PathVariable String name, @RequestParam("size") String size) { 27 | log.info("Making a {} {}...", size, name); 28 | Counter.builder("tea.make") 29 | .tags("name", name) 30 | .tags("size", size) 31 | .register(registry) 32 | .increment(); 33 | 34 | return teaService.make(name, size); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/config/ActuatorConfig.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.config; 2 | 3 | import io.micrometer.observation.ObservationPredicate; 4 | import org.example.teahouse.core.actuator.health.HealthClientAdapter; 5 | import org.example.teahouse.tea.tealeaf.TealeafClient; 6 | import org.example.teahouse.tea.water.WaterClient; 7 | 8 | import org.springframework.boot.actuate.health.HealthIndicator; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.http.server.observation.ServerRequestObservationContext; 12 | 13 | @Configuration 14 | public class ActuatorConfig { 15 | @Bean 16 | public HealthIndicator tealeafServiceHealthIndicator(TealeafClient tealeafClient) { 17 | return new HealthClientAdapter(tealeafClient); 18 | } 19 | 20 | @Bean 21 | public HealthIndicator waterServiceHealthIndicator(WaterClient waterClient) { 22 | return new HealthClientAdapter(waterClient); 23 | } 24 | 25 | @Bean 26 | ObservationPredicate noUiResourceObservations() { 27 | return (name, context) -> { 28 | if (name.equals("http.server.requests") && context instanceof ServerRequestObservationContext serverContext) { 29 | return !serverContext.getCarrier().getRequestURI().startsWith("/assets/"); 30 | } 31 | else { 32 | return true; 33 | } 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/repo/Water.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.repo; 2 | 3 | import static lombok.AccessLevel.PRIVATE; 4 | 5 | import java.util.UUID; 6 | import jakarta.persistence.Column; 7 | import jakarta.persistence.Entity; 8 | import jakarta.persistence.GeneratedValue; 9 | import jakarta.persistence.Id; 10 | import lombok.Builder; 11 | import lombok.NoArgsConstructor; 12 | import lombok.RequiredArgsConstructor; 13 | import lombok.Value; 14 | import org.example.teahouse.water.api.CreateWaterRequest; 15 | import org.example.teahouse.water.controller.RepresentationWaterModel; 16 | 17 | @Entity 18 | @Value 19 | @Builder 20 | @RequiredArgsConstructor 21 | @NoArgsConstructor(force = true, access = PRIVATE) 22 | public class Water { 23 | @Id @GeneratedValue 24 | private final UUID id; 25 | 26 | @Column(unique = true, nullable = false) 27 | private final String size; 28 | 29 | @Column(unique=true, nullable = false) 30 | private final String amount; 31 | 32 | public RepresentationWaterModel toRepresentationWaterModel() { 33 | return RepresentationWaterModel.builder() 34 | .id(this.id) 35 | .size(this.size) 36 | .amount(this.amount) 37 | .build(); 38 | } 39 | 40 | public static Water fromCreateWaterRequest(CreateWaterRequest createWaterRequest) { 41 | return Water.builder() 42 | .size(createWaterRequest.getSize()) 43 | .amount(createWaterRequest.getAmount()) 44 | .build(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/MakeTeaDocumentation.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import io.micrometer.common.docs.KeyName; 4 | import io.micrometer.common.lang.NonNull; 5 | import io.micrometer.observation.Observation; 6 | import io.micrometer.observation.ObservationConvention; 7 | import io.micrometer.observation.docs.ObservationDocumentation; 8 | 9 | public enum MakeTeaDocumentation implements ObservationDocumentation { 10 | /** 11 | * Make some tea. 12 | */ 13 | MAKE_TEA { 14 | @Override 15 | public Class> getDefaultConvention() { 16 | return DefaultMakeTeaConvention.class; 17 | } 18 | 19 | @NonNull 20 | @Override 21 | public KeyName[] getLowCardinalityKeyNames() { 22 | return LowCardinalityKeyNames.values(); 23 | } 24 | }; 25 | 26 | enum LowCardinalityKeyNames implements KeyName { 27 | /** 28 | * Name that uniquely identifies a tea-leaf. 29 | */ 30 | TEA_LEAF_NAME { 31 | @NonNull 32 | @Override 33 | public String asString() { 34 | return "tea.name"; 35 | } 36 | }, 37 | /** 38 | * Water size (small, medium, large). 39 | */ 40 | WATER_SIZE { 41 | @NonNull 42 | @Override 43 | public String asString() { 44 | return "water.size"; 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/controller/WaterModelAssembler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.controller; 2 | 3 | import static org.springframework.hateoas.IanaLinkRelations.COLLECTION; 4 | import static org.springframework.hateoas.IanaLinkRelations.SEARCH; 5 | import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; 6 | import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; 7 | 8 | import org.example.teahouse.water.api.WaterModel; 9 | import org.example.teahouse.water.repo.Water; 10 | import org.springframework.hateoas.server.EntityLinks; 11 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class WaterModelAssembler extends RepresentationModelAssemblerSupport { 16 | private final EntityLinks links; 17 | 18 | public WaterModelAssembler(EntityLinks entityLinks) { 19 | super(WaterController.class, RepresentationWaterModel.class); 20 | this.links = entityLinks; 21 | } 22 | 23 | @Override 24 | protected RepresentationWaterModel instantiateModel(Water water) { 25 | return water.toRepresentationWaterModel(); 26 | } 27 | 28 | @Override 29 | public RepresentationWaterModel toModel(Water water) { 30 | return createModelWithId(water.getId(), water) 31 | .add(linkTo(methodOn(WaterController.class).findBySize(water.getSize())).withRel(SEARCH)) 32 | .add(links.linkToCollectionResource(WaterModel.class).withRel(COLLECTION)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/logback-access.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${accessLogPattern} 11 | 12 | 13 | 14 | 15 | 16 | ${accessLogPattern} 17 | 18 | ${fileName} 19 | 20 | ${fileName}.%i 21 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/controller/TealeafModelAssembler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.controller; 2 | 3 | import static org.springframework.hateoas.IanaLinkRelations.COLLECTION; 4 | import static org.springframework.hateoas.IanaLinkRelations.SEARCH; 5 | import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; 6 | import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; 7 | 8 | import org.example.teahouse.tealeaf.api.TealeafModel; 9 | import org.example.teahouse.tealeaf.repo.Tealeaf; 10 | import org.springframework.hateoas.server.EntityLinks; 11 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class TealeafModelAssembler extends RepresentationModelAssemblerSupport { 16 | private final EntityLinks links; 17 | 18 | public TealeafModelAssembler(EntityLinks entityLinks) { 19 | super(TealeafController.class, RepresentationTealeafModel.class); 20 | this.links = entityLinks; 21 | } 22 | 23 | @Override 24 | protected RepresentationTealeafModel instantiateModel(Tealeaf tealeaf) { 25 | return tealeaf.toRepresentationTealeafModel(); 26 | } 27 | 28 | @Override 29 | public RepresentationTealeafModel toModel(Tealeaf tealeaf) { 30 | return createModelWithId(tealeaf.getId(), tealeaf) 31 | .add(linkTo(methodOn(TealeafController.class).findByName(tealeaf.getName())).withRel(SEARCH)) 32 | .add(links.linkToCollectionResource(TealeafModel.class).withRel(COLLECTION)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /eureka/src/main/resources/logback-access.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${accessLogPattern} 11 | 12 | 13 | 14 | 15 | 16 | ${accessLogPattern} 17 | 18 | ${fileName} 19 | 20 | ${fileName}.%i 21 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /water-service/src/main/resources/logback-access.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${accessLogPattern} 11 | 12 | 13 | 14 | 15 | 16 | ${accessLogPattern} 17 | 18 | ${fileName} 19 | 20 | ${fileName}.%i 21 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/logback-access.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${accessLogPattern} 11 | 12 | 13 | 14 | 15 | 16 | ${accessLogPattern} 17 | 18 | ${fileName} 19 | 20 | ${fileName}.%i 21 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /spring-boot-admin/src/main/resources/logback-access.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${accessLogPattern} 11 | 12 | 13 | 14 | 15 | 16 | ${accessLogPattern} 17 | 18 | ${fileName} 19 | 20 | ${fileName}.%i 21 | 22 | 23 | 10MB 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /tea-service/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: "$rootDir/gradle/spring-boot.gradle" 2 | 3 | configurations { 4 | adoc 5 | } 6 | 7 | dependencies { 8 | implementation project(':water-service:water-api') 9 | implementation project(':tealeaf-service:tealeaf-api') 10 | implementation project(':tea-service:tea-api') 11 | 12 | implementation 'org.springframework.boot:spring-boot-starter-hateoas' 13 | implementation 'org.springframework.boot:spring-boot-starter-validation' 14 | implementation 'org.springframework.boot:spring-boot-starter-data-rest' 15 | implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 16 | 17 | implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' 18 | implementation 'io.github.openfeign:feign-okhttp' 19 | implementation 'io.github.openfeign:feign-micrometer' 20 | 21 | implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' 22 | implementation 'io.micrometer:micrometer-tracing-bridge-brave' 23 | implementation 'io.zipkin.reporter2:zipkin-reporter-brave' 24 | 25 | implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.+' 26 | 27 | implementation 'org.zalando:logbook-spring-boot-starter:3.+' 28 | implementation 'org.zalando:logbook-okhttp:3.+' 29 | 30 | runtimeOnly 'com.github.loki4j:loki-logback-appender:1.+' 31 | 32 | adoc 'io.micrometer:micrometer-docs-generator:1.+' 33 | } 34 | 35 | tasks.register('asciidoctor', JavaExec) { 36 | mainClass = 'io.micrometer.docs.DocsGeneratorCommand' 37 | classpath configurations.adoc 38 | // input folder, inclusion pattern, output folder 39 | args projectDir.path, '.*', project.layout.buildDirectory.dir('asciidoctor').get().asFile.path 40 | } 41 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/observation/PianoObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.observation; 2 | 3 | import javax.sound.midi.MidiChannel; 4 | import javax.sound.midi.MidiUnavailableException; 5 | 6 | import io.micrometer.common.lang.NonNull; 7 | import io.micrometer.core.instrument.MeterRegistry; 8 | import io.micrometer.observation.Observation; 9 | import jakarta.annotation.Nonnull; 10 | import net.ttddyy.observation.tracing.ConnectionContext; 11 | import net.ttddyy.observation.tracing.DataSourceBaseContext; 12 | import org.example.teahouse.core.observation.AbstractMidiObservationHandler; 13 | 14 | import org.springframework.context.annotation.Profile; 15 | import org.springframework.stereotype.Component; 16 | 17 | @Component 18 | @Profile("midi") 19 | public class PianoObservationHandler extends AbstractMidiObservationHandler { 20 | 21 | private final MidiChannel piano; 22 | 23 | public PianoObservationHandler(MeterRegistry registry) throws MidiUnavailableException { 24 | super(registry); 25 | // ch #0 is set to Acoustic Grand Piano by default 26 | this.piano = this.synthesizer.getChannels()[0]; 27 | } 28 | 29 | @Nonnull 30 | @Override 31 | protected Note contextToNote(@Nonnull DataSourceBaseContext context) { 32 | // int[] notes = {36, 38, 40, 43, 45}; // C2-A2 33 | // int[] notes = {48, 50, 52, 55, 57}; // C3-A3 34 | 35 | // C major pentatonic scale: C4 (60), D4(62), E4 (64), G4 (67), A4 (69) 36 | int[] notes = {60, 62, 64, 67, 69}; 37 | return new Note(this.piano, randomNote(notes), 64, duration(context)); 38 | } 39 | 40 | @Override 41 | public boolean supportsContext(@NonNull Observation.Context context) { 42 | return context instanceof ConnectionContext; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/observation/BassObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.observation; 2 | 3 | import javax.sound.midi.MidiChannel; 4 | import javax.sound.midi.MidiUnavailableException; 5 | 6 | import feign.micrometer.FeignContext; 7 | import io.micrometer.common.lang.NonNull; 8 | import io.micrometer.core.instrument.MeterRegistry; 9 | import io.micrometer.observation.Observation; 10 | import jakarta.annotation.Nonnull; 11 | import org.example.teahouse.core.observation.AbstractMidiObservationHandler; 12 | 13 | import org.springframework.context.annotation.Profile; 14 | import org.springframework.stereotype.Component; 15 | 16 | @Component 17 | @Profile("midi") 18 | public class BassObservationHandler extends AbstractMidiObservationHandler { 19 | 20 | private final MidiChannel bass; 21 | 22 | public BassObservationHandler(MeterRegistry registry) throws MidiUnavailableException { 23 | super(registry); 24 | this.bass = synthesizer.getChannels()[0]; 25 | // Slap Bass 1 is bank #0 preset #36 26 | this.bass.programChange(synthesizer.getAvailableInstruments()[36].getPatch().getProgram()); 27 | } 28 | 29 | @Nonnull 30 | @Override 31 | protected Note contextToNote(@Nonnull FeignContext context) { 32 | // C major pentatonic scale from E2 on the bass: E2 (40), G2(43), A2 (45), C3 (48), D3 (50), E3 (52) 33 | int[] notes = {40, 43, 45, 48, 50, 52}; 34 | return new Note(this.bass, randomNote(notes), 64, duration(context)); 35 | } 36 | 37 | @Override 38 | public boolean supportsContext(@NonNull Observation.Context context) { 39 | // Only for water-service, there is also tealeaf-service 40 | return context instanceof FeignContext feignContext 41 | && feignContext.getCarrier().url().contains("/waters/"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/TeaServiceApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea; 2 | 3 | import io.micrometer.observation.ObservationRegistry; 4 | import org.example.teahouse.tea.service.DefaultTeaService; 5 | import org.example.teahouse.tea.service.MakeTeaConvention; 6 | import org.example.teahouse.tea.service.ObservedTeaService; 7 | import org.example.teahouse.tea.service.TeaService; 8 | import org.example.teahouse.tea.tealeaf.TealeafClient; 9 | import org.example.teahouse.tea.water.WaterClient; 10 | 11 | import org.springframework.beans.factory.ObjectProvider; 12 | import org.springframework.boot.SpringApplication; 13 | import org.springframework.boot.autoconfigure.SpringBootApplication; 14 | import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; 15 | import org.springframework.cloud.openfeign.EnableFeignClients; 16 | import org.springframework.context.annotation.Bean; 17 | import org.springframework.context.annotation.ComponentScan; 18 | import org.springframework.context.annotation.PropertySource; 19 | 20 | @EnableFeignClients 21 | @SpringBootApplication 22 | @PropertySource("classpath:build.properties") 23 | @ComponentScan(basePackages = { "org.example.teahouse" }) 24 | public class TeaServiceApplication { 25 | public static void main(String[] args) { 26 | SpringApplication springApplication = new SpringApplication(TeaServiceApplication.class); 27 | springApplication.setApplicationStartup(new BufferingApplicationStartup(10_000)); 28 | springApplication.run(args); 29 | } 30 | 31 | @Bean 32 | TeaService teaService(WaterClient waterClient, TealeafClient tealeafClient, ObservationRegistry registry, ObjectProvider customConvention) { 33 | return new ObservedTeaService(new DefaultTeaService(waterClient, tealeafClient), registry, customConvention.getIfAvailable()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | load: 2 | while true; do \ 3 | curl --silent --output /dev/null http://localhost:8090/tea/sencha?size=small; \ 4 | sleep 0.5; \ 5 | curl --silent --output /dev/null http://localhost:8090/tea/english%20breakfast?size=small; \ 6 | sleep 0.5; \ 7 | done \ 8 | 9 | chaos: 10 | docker exec toxiproxy /toxiproxy-cli toxic add --toxicName base-latency --type latency --downstream --toxicity 1.0 --attribute latency=50 --attribute jitter=0 water-db 11 | # in order to make tail-latency work, you need to disable the DB connection pool (HikariCP) 12 | # since ToxiProxy injects latency on the connection (TCP) level 13 | # and a new connection is needed to inject latency for less than 100% or the connections 14 | #docker exec toxiproxy /toxiproxy-cli toxic add --toxicName tail-latency --type latency --downstream --toxicity 0.005 --attribute latency=150 --attribute jitter=0 water-db 15 | 16 | big-chaos: 17 | docker exec toxiproxy /toxiproxy-cli toxic add --toxicName base-latency --type latency --downstream --toxicity 1.0 --attribute latency=300 --attribute jitter=0 water-db 18 | 19 | order: 20 | docker exec toxiproxy /toxiproxy-cli toxic remove --toxicName base-latency water-db 21 | #docker exec toxiproxy /toxiproxy-cli toxic remove --toxicName tail-latency water-db 22 | 23 | errors: 24 | TEA_URL=$(shell http ':8092/tealeaves/search/findByName?name=english+breakfast' | jq --raw-output '._links.self.href'); \ 25 | http DELETE $$TEA_URL 26 | 27 | errors-fixed: 28 | http POST ':8092/tealeaves' --raw '{ "name": "english breakfast", "type": "black", "suggestedAmount": "5 g", "suggestedWaterTemperature": "99 °C", "suggestedSteepingTime": "3 min" }' 29 | 30 | notification-server: 31 | # ncat --listen --keep-open --verbose --source-port 3333 --sh-exec 'tee /dev/tty | echo HTTP/1.1 200 OK\\r\\n' 32 | ncat --listen --keep-open --verbose --source-port 3333 --sh-exec "noti -t 'I cannot drink tea!' -m 'Please do something!' && echo 'HTTP/1.1 200 OK\\r\\n'" 33 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | ${FILE_LOG_PATTERN} 12 | 13 | ${payloadFileName} 14 | 15 | ${payloadFileName}.%i 16 | 17 | 18 | 10MB 19 | 20 | 21 | 22 | 23 | 24 | http://localhost:3100/loki/api/v1/push 25 | 26 | 27 | 30 | 31 | ${FILE_LOG_PATTERN} 32 | 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /water-service/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | ${FILE_LOG_PATTERN} 12 | 13 | ${payloadFileName} 14 | 15 | ${payloadFileName}.%i 16 | 17 | 18 | 10MB 19 | 20 | 21 | 22 | 23 | 24 | http://localhost:3100/loki/api/v1/push 25 | 26 | 27 | 30 | 31 | ${FILE_LOG_PATTERN} 32 | 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | ${FILE_LOG_PATTERN} 12 | 13 | ${payloadFileName} 14 | 15 | ${payloadFileName}.%i 16 | 17 | 18 | 10MB 19 | 20 | 21 | 22 | 23 | 24 | http://localhost:3100/loki/api/v1/push 25 | 26 | 27 | 30 | 31 | ${FILE_LOG_PATTERN} 32 | 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/observation/PercussionObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.observation; 2 | 3 | import javax.sound.midi.MidiChannel; 4 | import javax.sound.midi.MidiUnavailableException; 5 | 6 | import io.micrometer.core.instrument.MeterRegistry; 7 | import io.micrometer.observation.Observation; 8 | import jakarta.annotation.Nonnull; 9 | import org.example.teahouse.core.observation.AbstractMidiObservationHandler; 10 | 11 | import org.springframework.context.annotation.Profile; 12 | import org.springframework.http.server.observation.ServerRequestObservationContext; 13 | import org.springframework.stereotype.Component; 14 | 15 | @Component 16 | @Profile("midi") 17 | public class PercussionObservationHandler extends AbstractMidiObservationHandler { 18 | 19 | private final MidiChannel percussion; 20 | 21 | private final MidiChannel frenchHorn; 22 | 23 | public PercussionObservationHandler(MeterRegistry registry) throws MidiUnavailableException { 24 | super(registry); 25 | // ch #9 is for percussion 26 | this.percussion = this.synthesizer.getChannels()[9]; 27 | this.frenchHorn = this.synthesizer.getChannels()[0]; 28 | // French Horn is bank #0 preset #60 29 | this.frenchHorn.programChange(synthesizer.getAvailableInstruments()[60].getPatch().getProgram()); 30 | } 31 | 32 | @Nonnull 33 | @Override 34 | protected Note contextToNote(@Nonnull ServerRequestObservationContext context) { 35 | long duration = duration(context); 36 | if (context.getError() != null) { 37 | // play C4 (middle C) 38 | return new Note(this.frenchHorn, 60, 90, duration); 39 | } 40 | else { 41 | // play something on a random percussion 42 | // from #35 to #52; not every percussion is available in Java 43 | return new Note(this.percussion, randomNote(35, 53), 64, duration); 44 | } 45 | } 46 | 47 | @Override 48 | public boolean supportsContext(@Nonnull Observation.Context context) { 49 | return context instanceof ServerRequestObservationContext; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /water-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=water-service 2 | spring.application.org=teahouse 3 | spring.profiles.default=local 4 | server.port=8091 5 | 6 | spring.output.ansi.enabled=always 7 | spring.jackson.serialization.indent_output=true 8 | spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat 9 | 10 | spring.mvc.problemdetails.enabled=true 11 | 12 | logging.file.name=${spring.application.home:.}/logs/${spring.application.name}.log 13 | logbook.predicate.exclude[0].path=/actuator/** 14 | 15 | management.endpoints.web.exposure.include=* 16 | management.endpoint.health.show-details=always 17 | management.endpoint.env.show-values=always 18 | management.info.env.enabled=true 19 | management.info.java.enabled=true 20 | management.info.os.enabled=true 21 | management.info.process.enabled=true 22 | 23 | spring.cloud.discovery.client.composite-indicator.enabled=false 24 | 25 | management.observations.key-values.org=${spring.application.org} 26 | management.metrics.tags.application=${spring.application.name} 27 | management.metrics.tags.org=${spring.application.org} 28 | management.metrics.tags.profiles=${spring.profiles.active} 29 | management.prometheus.metrics.export.step=10s 30 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 31 | management.tracing.sampling.probability=1.0 32 | 33 | server.tomcat.mbeanregistry.enabled=true 34 | 35 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 36 | logging.level.com.netflix.discovery=OFF 37 | 38 | spring.datasource.url=jdbc:h2:mem:water-db;MODE=MySQL 39 | spring.datasource.username=sa 40 | spring.datasource.password=password 41 | 42 | spring.jpa.hibernate.ddl-auto=validate 43 | spring.h2.console.enabled=true 44 | 45 | jdbc.datasource-proxy.query.enable-logging=true 46 | jdbc.datasource-proxy.query.log-level=INFO 47 | jdbc.datasource-proxy.include-parameter-values=true 48 | 49 | # Generate schema creation script 50 | #spring.jpa.properties.hibernate.hbm2ddl.delimiter=; 51 | #spring.jpa.properties.jakarta.persistence.schema-generation.scripts.action=create 52 | #spring.jpa.properties.jakarta.persistence.schema-generation.scripts.create-target=create.sql 53 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=tealeaf-service 2 | spring.application.org=teahouse 3 | spring.profiles.default=local 4 | server.port=8092 5 | 6 | spring.output.ansi.enabled=always 7 | spring.jackson.serialization.indent_output=true 8 | spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat 9 | 10 | spring.mvc.problemdetails.enabled=true 11 | 12 | logging.file.name=${spring.application.home:.}/logs/${spring.application.name}.log 13 | logbook.predicate.exclude[0].path=/actuator/** 14 | 15 | management.endpoints.web.exposure.include=* 16 | management.endpoint.health.show-details=always 17 | management.endpoint.env.show-values=always 18 | management.info.env.enabled=true 19 | management.info.java.enabled=true 20 | management.info.os.enabled=true 21 | management.info.process.enabled=true 22 | 23 | spring.cloud.discovery.client.composite-indicator.enabled=false 24 | 25 | management.observations.key-values.org=${spring.application.org} 26 | management.metrics.tags.application=${spring.application.name} 27 | management.metrics.tags.org=${spring.application.org} 28 | management.metrics.tags.profiles=${spring.profiles.active} 29 | management.prometheus.metrics.export.step=10s 30 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 31 | management.tracing.sampling.probability=1.0 32 | 33 | server.tomcat.mbeanregistry.enabled=true 34 | 35 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 36 | logging.level.com.netflix.discovery=OFF 37 | 38 | spring.datasource.url=jdbc:h2:mem:tealeaf-db;MODE=MySQL 39 | spring.datasource.username=sa 40 | spring.datasource.password=password 41 | 42 | spring.jpa.hibernate.ddl-auto=validate 43 | spring.h2.console.enabled=true 44 | 45 | jdbc.datasource-proxy.query.enable-logging=true 46 | jdbc.datasource-proxy.query.log-level=INFO 47 | jdbc.datasource-proxy.include-parameter-values=true 48 | 49 | # Generate schema creation script 50 | #spring.jpa.properties.hibernate.hbm2ddl.delimiter=; 51 | #spring.jpa.properties.jakarta.persistence.schema-generation.scripts.action=create 52 | #spring.jpa.properties.jakarta.persistence.schema-generation.scripts.create-target=create.sql 53 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=tea-service 2 | spring.application.org=teahouse 3 | spring.profiles.default=local 4 | server.port=8090 5 | 6 | spring.output.ansi.enabled=always 7 | spring.jackson.serialization.indent_output=true 8 | spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat 9 | 10 | spring.mvc.problemdetails.enabled=true 11 | 12 | logging.file.name=${spring.application.home:.}/logs/${spring.application.name}.log 13 | logbook.predicate.exclude[0].path=/actuator/** 14 | 15 | management.endpoints.web.exposure.include=* 16 | management.endpoint.health.show-details=always 17 | management.endpoint.env.show-values=always 18 | management.info.env.enabled=true 19 | management.info.java.enabled=true 20 | management.info.os.enabled=true 21 | management.info.process.enabled=true 22 | 23 | spring.cloud.discovery.client.composite-indicator.enabled=false 24 | 25 | management.observations.key-values.org=${spring.application.org} 26 | management.metrics.tags.application=${spring.application.name} 27 | management.metrics.tags.org=${spring.application.org} 28 | management.metrics.tags.profiles=${spring.profiles.active} 29 | management.prometheus.metrics.export.step=10s 30 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 31 | management.metrics.distribution.percentiles-histogram.http.client.requests=true 32 | management.tracing.sampling.probability=1.0 33 | 34 | server.tomcat.mbeanregistry.enabled=true 35 | 36 | spring.cloud.openfeign.okhttp.enabled=true 37 | 38 | spring.cloud.openfeign.client.config.water.url=http://localhost:8091 39 | spring.cloud.openfeign.client.config.water.connect-timeout=100 40 | spring.cloud.openfeign.client.config.water.read-timeout=5000 41 | 42 | spring.cloud.openfeign.client.config.tealeaf.url=http://localhost:8092 43 | spring.cloud.openfeign.client.config.tealeaf.connect-timeout=100 44 | spring.cloud.openfeign.client.config.tealeaf.read-timeout=5000 45 | 46 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 47 | logging.level.org.example.teahouse.tea.water.WaterClient=DEBUG 48 | logging.level.org.example.teahouse.tea.tealeaf.TealeafClient=DEBUG 49 | logging.level.com.netflix.discovery=OFF 50 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/repo/Tealeaf.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.repo; 2 | 3 | import static lombok.AccessLevel.PRIVATE; 4 | 5 | import java.util.UUID; 6 | import jakarta.persistence.Column; 7 | import jakarta.persistence.Entity; 8 | import jakarta.persistence.GeneratedValue; 9 | import jakarta.persistence.Id; 10 | import lombok.Builder; 11 | import lombok.NoArgsConstructor; 12 | import lombok.RequiredArgsConstructor; 13 | import lombok.Value; 14 | import org.example.teahouse.tealeaf.api.CreateTealeafRequest; 15 | import org.example.teahouse.tealeaf.controller.RepresentationTealeafModel; 16 | 17 | @Entity 18 | @Value 19 | @Builder 20 | @RequiredArgsConstructor 21 | @NoArgsConstructor(force = true, access = PRIVATE) 22 | public class Tealeaf { 23 | @Id @GeneratedValue 24 | private final UUID id; 25 | 26 | @Column(unique = true, nullable = false) 27 | private final String name; 28 | 29 | @Column(nullable = false) 30 | private final String type; 31 | 32 | @Column(nullable = false) 33 | private final String suggestedAmount; 34 | 35 | @Column(nullable = false) 36 | private final String suggestedWaterTemperature; 37 | 38 | @Column(nullable = false) 39 | private final String suggestedSteepingTime; 40 | 41 | public RepresentationTealeafModel toRepresentationTealeafModel() { 42 | return RepresentationTealeafModel.builder() 43 | .id(this.id) 44 | .name(this.name) 45 | .type(this.type) 46 | .suggestedAmount(this.suggestedAmount) 47 | .suggestedWaterTemperature(this.suggestedWaterTemperature) 48 | .suggestedSteepingTime(this.suggestedSteepingTime) 49 | .build(); 50 | } 51 | 52 | public static Tealeaf fromCreateTealeafRequest(CreateTealeafRequest createTealeafRequest) { 53 | return Tealeaf.builder() 54 | .name(createTealeafRequest.getName()) 55 | .type(createTealeafRequest.getType()) 56 | .suggestedAmount(createTealeafRequest.getSuggestedAmount()) 57 | .suggestedWaterTemperature(createTealeafRequest.getSuggestedWaterTemperature()) 58 | .suggestedSteepingTime(createTealeafRequest.getSuggestedSteepingTime()) 59 | .build(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /load-gen/src/gatling/java/org/example/teahouse/simulations/steep/SteepTeaSimulation.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.simulations.steep; 2 | 3 | import java.time.Duration; 4 | 5 | import io.gatling.javaapi.core.ChainBuilder; 6 | import io.gatling.javaapi.core.Simulation; 7 | import io.gatling.javaapi.http.HttpProtocolBuilder; 8 | 9 | import static io.gatling.http.HeaderNames.ContentType; 10 | import static io.gatling.http.HeaderNames.Accept; 11 | import static io.gatling.http.HeaderValues.ApplicationJson; 12 | import static io.gatling.javaapi.core.CoreDsl.constantUsersPerSec; 13 | import static io.gatling.javaapi.core.CoreDsl.exec; 14 | import static io.gatling.javaapi.core.CoreDsl.scenario; 15 | import static io.gatling.javaapi.http.HttpDsl.http; 16 | 17 | public class SteepTeaSimulation extends Simulation { 18 | final Duration duration = Duration.ofMinutes(120); 19 | final int usersPerSec = 5; 20 | 21 | final HttpProtocolBuilder httpProtocol = http.baseUrl("http://localhost:8090") 22 | .contentTypeHeader(ApplicationJson()) 23 | .acceptHeader(ApplicationJson()); 24 | 25 | final ChainBuilder makeRandomTea = exec(http("makeRandomTea") 26 | .get(session -> "/tea/%s".formatted(generateTeaName())) 27 | .queryParam("size", session -> generateTeaSize()) 28 | .header(ContentType(), ApplicationJson()) 29 | .header(Accept(), ApplicationJson()) 30 | ); 31 | 32 | String generateTeaName() { 33 | double random = Math.random(); 34 | if (random < 0.1) return "english breakfast"; 35 | else if (random < 0.7) return "sencha"; 36 | else if (random < 0.9) return "da hong pao"; 37 | else return "gyokuro"; 38 | } 39 | 40 | String generateTeaSize() { 41 | double random = Math.random(); 42 | if (random < 0.5) return "small"; 43 | else if (random < 0.75) return "medium"; 44 | else return "large"; 45 | } 46 | 47 | { 48 | System.out.println(("duration: %s".formatted(duration))); 49 | System.out.println(("constantUsersPerSec: %d".formatted(usersPerSec))); 50 | setUp(scenario("steepTea") 51 | .exec(makeRandomTea) 52 | .injectOpen(constantUsersPerSec(usersPerSec).during(duration)) 53 | ).protocols(httpProtocol); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /docker/grafana/provisioning/datasources/datasource.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | 3 | datasources: 4 | - name: Prometheus 5 | type: prometheus 6 | uid: prometheus 7 | access: proxy 8 | url: http://host.docker.internal:9090 9 | editable: true 10 | jsonData: 11 | httpMethod: POST 12 | exemplarTraceIdDestinations: 13 | - name: trace_id 14 | datasourceUid: tempo 15 | # if you want to use zipkin 16 | # url: http://localhost:9411/zipkin/traces/$${__value.raw} 17 | - name: Tempo 18 | type: tempo 19 | uid: tempo 20 | access: proxy 21 | url: http://host.docker.internal:3200 22 | isDefault: true 23 | editable: true 24 | jsonData: 25 | httpMethod: GET 26 | tracesToMetrics: 27 | datasourceUid: prometheus 28 | tags: [{ key: 'service.name', value: 'application' }, { key: 'org' }, { key: 'method' }, { key: 'uri' }, { key: 'outcome' }, { key: 'status' }, { key: 'exception' }] 29 | queries: 30 | - name: 'Throughput' 31 | query: 'sum(rate(http_server_requests_seconds_count{$$__tags}[$$__rate_interval]))' 32 | - name: 'Latency' 33 | query: 'histogram_quantile(1.00, sum(rate(http_server_requests_seconds_bucket{$$__tags}[$$__rate_interval])) by (le))' 34 | spanStartTimeShift: '-10m' 35 | spanEndTimeShift: '10m' 36 | tracesToLogs: 37 | datasourceUid: loki 38 | mappedTags: [{ key: 'org' }] 39 | mapTagNamesEnabled: true 40 | filterByTraceID: true 41 | filterBySpanID: false 42 | spanStartTimeShift: '-10m' 43 | spanEndTimeShift: '10m' 44 | lokiSearch: 45 | datasourceUid: loki 46 | serviceMap: 47 | datasourceUid: prometheus 48 | nodeGraph: 49 | enabled: true 50 | - name: Loki 51 | type: loki 52 | uid: loki 53 | access: proxy 54 | url: http://host.docker.internal:3100 55 | editable: true 56 | jsonData: 57 | maxLines: 50 58 | derivedFields: 59 | - datasourceUid: tempo 60 | matcherRegex: '.+ --- \[.+\] \[.+\] \[(\w*)-\w*\] .+' 61 | name: traceId 62 | url: $${__value.raw} 63 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/ObservedTeaService.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import java.util.Collection; 4 | 5 | import io.micrometer.common.lang.Nullable; 6 | import io.micrometer.observation.ObservationRegistry; 7 | import org.example.teahouse.tea.api.TeaResponse; 8 | import org.example.teahouse.tealeaf.api.SimpleTealeafModel; 9 | import org.example.teahouse.water.api.SimpleWaterModel; 10 | 11 | public class ObservedTeaService implements TeaService { 12 | private final static MakeTeaConvention DEFAULT_CONVENTION = new DefaultMakeTeaConvention(); 13 | private final TeaService delegate; 14 | private final ObservationRegistry registry; 15 | @Nullable 16 | private final MakeTeaConvention customConvention; 17 | 18 | public ObservedTeaService(TeaService delegate, ObservationRegistry registry) { 19 | this(delegate, registry, null); 20 | } 21 | 22 | public ObservedTeaService(TeaService delegate, ObservationRegistry registry, @Nullable MakeTeaConvention customConvention) { 23 | this.delegate = delegate; 24 | this.registry = registry; 25 | this.customConvention = customConvention; 26 | } 27 | 28 | @Override 29 | public TeaResponse make(String name, String size) { 30 | // return Observation.createNotStarted("make.tea", registry) 31 | // .lowCardinalityKeyValue("tea.name", name) 32 | // .lowCardinalityKeyValue("water.size", size) 33 | // .observe(() -> delegate.make(name, size)); 34 | 35 | // return Observation.createNotStarted( 36 | // customConvention, 37 | // DEFAULT_CONVENTION, 38 | // () -> new MakeTeaContext(name, size), 39 | // registry) 40 | // .observe(() -> delegate.make(name, size)); 41 | 42 | return MakeTeaDocumentation.MAKE_TEA.observation( 43 | customConvention, 44 | DEFAULT_CONVENTION, 45 | () -> new MakeTeaContext(name, size), 46 | registry) 47 | .observe(() -> delegate.make(name, size)); 48 | } 49 | 50 | @Override 51 | public Collection tealeaves() { 52 | return delegate.tealeaves(); 53 | } 54 | 55 | @Override 56 | public Collection waters() { 57 | return delegate.waters(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/public/assets/steep.js: -------------------------------------------------------------------------------- 1 | $(document).ready(() => { 2 | $('#steep-it-button').click(fetchAndRenderData); 3 | $('#tealeaf-selector').keypress(event => onEnterPressed(event, fetchAndRenderData)); 4 | $('#water-selector').keypress(event => onEnterPressed(event, fetchAndRenderData)); 5 | }); 6 | 7 | function onEnterPressed(event, callback) { 8 | const keycode = event.keyCode ? event.keyCode : event.which; 9 | if (keycode == '13') { 10 | callback(); 11 | } 12 | } 13 | 14 | function fetchAndRenderData() { 15 | const name = $('#tealeaf-selector').val(); 16 | const size = $('#water-selector').val(); 17 | 18 | fetch(`/tea/${name}?size=${size}`) 19 | .then(renderData) 20 | .catch(renderError); 21 | } 22 | 23 | async function renderData(response) { 24 | if (response.ok) { 25 | renderTea(await response.json()); 26 | } 27 | else { 28 | renderErrorResponse(await response.json()); 29 | } 30 | } 31 | 32 | function renderTea(tea) { 33 | console.log(tea); 34 | 35 | $('#tea-header').text(`${tea.water.amount} ${tea.tealeaf.name}`); 36 | 37 | $('#steeping-time').text(`Steeping time: ${tea.steepingTime}`); 38 | $('#water-amount').text(`Amount of water: ${tea.water.amount}`); 39 | $('#water-temperature').text(`Temperature of water: ${tea.water.temperature}`); 40 | 41 | $('#tealeaves-name').text(`Name of tealeaves: ${tea.tealeaf.name}`); 42 | $('#tealeaves-type').text(`Type of tealeaves: ${tea.tealeaf.type}`); 43 | $('#tealeaves-amount').text(`Amount of tealeaves: ${tea.tealeaf.amount}`); 44 | 45 | $('#alert-container').attr('hidden', true); 46 | $('#tea-card-container').removeAttr('hidden'); 47 | } 48 | 49 | function renderErrorResponse(response) { 50 | if (response.status && response.title) { 51 | renderErrorMessage(`HTTP ${response.status}: ${response.title}`); 52 | } 53 | else if (response.error) { 54 | renderErrorMessage(response.error); 55 | } 56 | else { 57 | renderErrorMessage(response); 58 | } 59 | } 60 | 61 | function renderError(error) { 62 | renderErrorMessage(`Error while calling the backend: ${error}`); 63 | } 64 | 65 | function renderErrorMessage(errorMessage) { 66 | console.error(errorMessage); 67 | 68 | $('#tea-card-container').attr('hidden', true); 69 | $('#alert-container') 70 | .text(errorMessage) 71 | .removeAttr('hidden'); 72 | } 73 | -------------------------------------------------------------------------------- /gradle/spring-boot.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'org.springframework.boot' 2 | apply plugin: 'com.gorylenko.gradle-git-properties' 3 | apply plugin: 'org.cyclonedx.bom' 4 | 5 | ext.profiles = project.hasProperty('profiles') ? project.getProperty('profiles').split(',') : ['local'] // ./gradlew bootRun -Pprofiles=profileName 6 | 7 | dependencies { 8 | implementation project(':core') 9 | 10 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 11 | implementation 'org.springframework.boot:spring-boot-starter-web' 12 | implementation 'io.micrometer:micrometer-registry-prometheus' 13 | 14 | compileOnly 'org.springframework.boot:spring-boot-devtools' 15 | runtimeOnly 'org.jolokia:jolokia-core:1.+' 16 | 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | } 19 | 20 | bootJar.manifest.attributes += jar.manifest.attributes 21 | 22 | processResources { 23 | filesMatching('build.properties') { it.expand(project.properties) } 24 | } 25 | 26 | springBoot { 27 | buildInfo() 28 | } 29 | 30 | def commonjvmArgs = [ 31 | '-server', 32 | // '-XX:+PrintFlagsFinal', 33 | '-XX:NativeMemoryTracking=summary', 34 | // '-XX:+UnlockDiagnosticVMOptions', 35 | // '-XX:+PrintNMTStatistics', 36 | '-XX:MinHeapSize=256M', 37 | '-XX:MaxHeapSize=256M', 38 | '-XX:MaxMetaspaceSize=256M', 39 | '-XX:MaxDirectMemorySize=256M', 40 | '-XX:+HeapDumpOnOutOfMemoryError', 41 | "-XX:HeapDumpPath=$rootDir/logs", 42 | "-Xlog:gc*:file=$rootDir/logs/$project.name-gc.log:time,uptime,pid,tid,level,tags:filecount=5,filesize=5M", 43 | 44 | '-Djava.security.egd=file:/dev/./urandom', 45 | '-Duser.timezone=UTC', 46 | '-Dfile.encoding=UTF-8' 47 | ] 48 | 49 | mkdir "$rootDir/logs" 50 | bootRun { 51 | doFirst { 52 | if (isPortOpen('localhost', 3100) && 'loki' !in profiles) { // is Loki listening? 53 | profiles += 'loki' 54 | } 55 | jvmArgs += commonjvmArgs + [ 56 | "-Dspring.profiles.active=${profiles.join(',')}", 57 | "-Dspring.application.home=$rootDir" 58 | ] 59 | } 60 | } 61 | 62 | test { 63 | jvmArgs += commonjvmArgs + [ 64 | "-Dspring.application.home=$rootDir" 65 | ] 66 | } 67 | 68 | private static boolean isPortOpen(String host, int port) { 69 | try { 70 | new Socket(host, port).close() 71 | return true 72 | } 73 | catch (Exception exception) { 74 | return false 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/observation/SseObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.observation; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.LinkedBlockingQueue; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import io.micrometer.observation.Observation; 8 | import io.micrometer.observation.ObservationHandler; 9 | import jakarta.annotation.Nonnull; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import org.springframework.http.server.observation.ServerRequestObservationContext; 14 | import org.springframework.stereotype.Component; 15 | 16 | @Component 17 | public class SseObservationHandler implements ObservationHandler { 18 | 19 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | private final String startTimeKey = this.getClass().getName(); 22 | 23 | private final BlockingQueue queue; 24 | 25 | public SseObservationHandler() { 26 | this.queue = new LinkedBlockingQueue<>(1000); 27 | } 28 | 29 | @Override 30 | public void onStart(@Nonnull ServerRequestObservationContext context) { 31 | context.put(this.startTimeKey, System.nanoTime()); 32 | } 33 | 34 | @Override 35 | public void onStop(@Nonnull ServerRequestObservationContext context) { 36 | try { 37 | if (this.queue.remainingCapacity() < 1) { 38 | this.queue.poll(); 39 | } 40 | this.queue.put(contextToMessage(context)); 41 | } 42 | catch (InterruptedException e) { 43 | this.logger.warn("Unable to add message", e); 44 | } 45 | } 46 | 47 | @Override 48 | public boolean supportsContext(@Nonnull Observation.Context context) { 49 | return context instanceof ServerRequestObservationContext; 50 | } 51 | 52 | @Nonnull 53 | public String take() throws InterruptedException { 54 | return this.queue.take(); 55 | } 56 | 57 | @Nonnull 58 | private String contextToMessage(@Nonnull ServerRequestObservationContext context) { 59 | return "{\"name\": \"%s\", \"error\": %b, \"duration\": %d}".formatted(context.getName(), context.getError() !=null , duration(context)); 60 | } 61 | 62 | private long duration(@Nonnull Observation.Context context) { 63 | @SuppressWarnings("DataFlowIssue") 64 | long nanos = System.nanoTime() - context.get(this.startTimeKey); 65 | return TimeUnit.NANOSECONDS.toMillis(nanos); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/service/DefaultTeaService.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | import lombok.RequiredArgsConstructor; 7 | import org.example.teahouse.tea.api.TeaResponse; 8 | import org.example.teahouse.tea.api.Tealeaf; 9 | import org.example.teahouse.tea.api.Water; 10 | import org.example.teahouse.tea.tealeaf.TealeafClient; 11 | import org.example.teahouse.tea.water.WaterClient; 12 | import org.example.teahouse.tealeaf.api.SimpleTealeafModel; 13 | import org.example.teahouse.tealeaf.api.TealeafModel; 14 | import org.example.teahouse.water.api.SimpleWaterModel; 15 | import org.example.teahouse.water.api.WaterModel; 16 | 17 | import org.springframework.data.domain.PageRequest; 18 | import org.springframework.data.domain.Pageable; 19 | import org.springframework.hateoas.PagedModel; 20 | 21 | @RequiredArgsConstructor 22 | public class DefaultTeaService implements TeaService{ 23 | private final WaterClient waterClient; 24 | private final TealeafClient tealeafClient; 25 | 26 | @Override 27 | public TeaResponse make(String name, String size) { 28 | WaterModel waterModel = waterClient.findBySize(size); 29 | TealeafModel tealeafModel = tealeafClient.findByName(name); 30 | 31 | return TeaResponse.builder() 32 | .water( 33 | Water.builder() 34 | .amount(waterModel.getAmount()) 35 | .temperature(tealeafModel.getSuggestedWaterTemperature()) 36 | .build() 37 | ) 38 | .tealeaf( 39 | Tealeaf.builder() 40 | .name(tealeafModel.getName()) 41 | .type(tealeafModel.getType()) 42 | .amount(tealeafModel.getSuggestedAmount()) 43 | .build() 44 | ) 45 | .steepingTime(tealeafModel.getSuggestedSteepingTime()) 46 | .build(); 47 | } 48 | 49 | @Override 50 | public Collection tealeaves() { 51 | Pageable pageable = PageRequest.ofSize(20); // set to 1 to get one resource per request 52 | PagedModel tealeavesPage = tealeafClient.tealeaves(pageable); 53 | Collection tealeaves = new ArrayList<>(tealeavesPage.getContent()); 54 | 55 | while (tealeavesPage.getNextLink().isPresent()) { 56 | pageable = pageable.next(); 57 | tealeavesPage = tealeafClient.tealeaves(pageable); 58 | tealeaves.addAll(tealeavesPage.getContent()); 59 | } 60 | 61 | return tealeaves; 62 | } 63 | 64 | @Override 65 | public Collection waters() { 66 | return waterClient.waters(Pageable.unpaged()).getContent(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tea-service/tea-api/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | commons-codec:commons-codec:1.18.0=testCompileClasspath,testRuntimeClasspath 5 | commons-logging:commons-logging:1.2=testCompileClasspath,testRuntimeClasspath 6 | io.rest-assured:json-path:5.5.6=testCompileClasspath,testRuntimeClasspath 7 | io.rest-assured:rest-assured-common:5.5.6=testCompileClasspath,testRuntimeClasspath 8 | io.rest-assured:rest-assured:5.5.6=testCompileClasspath,testRuntimeClasspath 9 | io.rest-assured:xml-path:5.5.6=testCompileClasspath,testRuntimeClasspath 10 | org.apache.commons:commons-lang3:3.18.0=testCompileClasspath,testRuntimeClasspath 11 | org.apache.groovy:groovy-bom:4.0.29=testCompileClasspath,testRuntimeClasspath 12 | org.apache.groovy:groovy-json:4.0.29=testCompileClasspath,testRuntimeClasspath 13 | org.apache.groovy:groovy-xml:4.0.29=testCompileClasspath,testRuntimeClasspath 14 | org.apache.groovy:groovy:4.0.29=testCompileClasspath,testRuntimeClasspath 15 | org.apache.httpcomponents:httpclient:4.5.13=testCompileClasspath,testRuntimeClasspath 16 | org.apache.httpcomponents:httpcore:4.4.16=testCompileClasspath,testRuntimeClasspath 17 | org.apache.httpcomponents:httpmime:4.5.13=testCompileClasspath,testRuntimeClasspath 18 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 19 | org.ccil.cowan.tagsoup:tagsoup:1.2.1=testCompileClasspath,testRuntimeClasspath 20 | org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath 21 | org.junit.jupiter:junit-jupiter-api:5.14.1=testCompileClasspath,testRuntimeClasspath 22 | org.junit.jupiter:junit-jupiter-engine:5.14.1=testRuntimeClasspath 23 | org.junit.jupiter:junit-jupiter-params:5.14.1=testCompileClasspath,testRuntimeClasspath 24 | org.junit.jupiter:junit-jupiter:5.14.1=testCompileClasspath,testRuntimeClasspath 25 | org.junit.platform:junit-platform-commons:1.14.1=testCompileClasspath,testRuntimeClasspath 26 | org.junit.platform:junit-platform-engine:1.14.1=testRuntimeClasspath 27 | org.junit.platform:junit-platform-launcher:1.14.1=testRuntimeClasspath 28 | org.junit:junit-bom:5.14.1=testCompileClasspath,testRuntimeClasspath 29 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 30 | org.projectlombok:lombok:1.18.42=annotationProcessor,compileClasspath 31 | org.springframework.boot:spring-boot-dependencies:3.5.8=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 32 | org.springframework.cloud:spring-cloud-dependencies:2025.0.0=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 33 | org.springframework.data:spring-data-bom:2025.0.6=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 34 | empty=testAnnotationProcessor 35 | -------------------------------------------------------------------------------- /tea-service/src/main/java/org/example/teahouse/tea/observation/MelodyObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tea.observation; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | import javax.sound.midi.MidiChannel; 9 | import javax.sound.midi.MidiUnavailableException; 10 | 11 | import io.micrometer.core.instrument.MeterRegistry; 12 | import io.micrometer.observation.Observation; 13 | import jakarta.annotation.Nonnull; 14 | import org.example.teahouse.core.observation.AbstractMidiObservationHandler; 15 | 16 | import org.springframework.context.annotation.Profile; 17 | import org.springframework.http.server.observation.ServerRequestObservationContext; 18 | import org.springframework.stereotype.Component; 19 | 20 | @Component 21 | @Profile("melody") 22 | public class MelodyObservationHandler extends AbstractMidiObservationHandler { 23 | 24 | // D is D4, d is an octave higher (D5) 25 | // ₣ is mapped to F# so that every note can be encoded with one character 26 | private static final Map noteToNoteNumber = Map.of( 27 | "D", 62, 28 | "E", 64, 29 | "₣", 66, 30 | "G", 67, 31 | "A", 69, 32 | "B", 71, 33 | "d", 74 34 | ); 35 | 36 | private static final String melody = """ 37 | D E G E BBB BBB AAAAAA 38 | D E G E AAA AAA GGGGGG 39 | D E G E GGGG AAAAAA ₣₣ 40 | DD DD AAAA GGGGGGGG 41 | D E G E BBB BBB AAAAAA 42 | D E G E dddd ₣₣ GGGGGG 43 | D E G E GGGG AA ₣₣₣₣₣₣ 44 | DD AAAA GGGGGGGG 45 | """; 46 | 47 | private final MidiChannel channel; 48 | 49 | private final List program; 50 | 51 | private final AtomicInteger programPosition = new AtomicInteger(); 52 | 53 | public MelodyObservationHandler(MeterRegistry registry) throws MidiUnavailableException { 54 | super(registry); 55 | // ch #0 is set to Acoustic Grand Piano by default 56 | this.channel = this.synthesizer.getChannels()[0]; 57 | this.program = Arrays.stream(melody.split("[ \n]")) 58 | .map(this::toNote) 59 | .toList(); 60 | } 61 | 62 | @Nonnull 63 | @Override 64 | protected Note contextToNote(@Nonnull ServerRequestObservationContext context) { 65 | return program.get(programPosition.getAndIncrement() % program.size()); 66 | } 67 | 68 | @Override 69 | public boolean supportsContext(@Nonnull Observation.Context context) { 70 | return context instanceof ServerRequestObservationContext; 71 | } 72 | 73 | private Note toNote(String encodedNote) { 74 | Integer noteNumber = noteToNoteNumber.get(encodedNote.substring(0, 1)); 75 | return new Note(channel, noteNumber, 64, encodedNote.length() * 120L); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /water-service/water-api/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | commons-codec:commons-codec:1.18.0=testCompileClasspath,testRuntimeClasspath 5 | commons-logging:commons-logging:1.2=testCompileClasspath,testRuntimeClasspath 6 | io.rest-assured:json-path:5.5.6=testCompileClasspath,testRuntimeClasspath 7 | io.rest-assured:rest-assured-common:5.5.6=testCompileClasspath,testRuntimeClasspath 8 | io.rest-assured:rest-assured:5.5.6=testCompileClasspath,testRuntimeClasspath 9 | io.rest-assured:xml-path:5.5.6=testCompileClasspath,testRuntimeClasspath 10 | jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 11 | org.apache.commons:commons-lang3:3.18.0=testCompileClasspath,testRuntimeClasspath 12 | org.apache.groovy:groovy-bom:4.0.29=testCompileClasspath,testRuntimeClasspath 13 | org.apache.groovy:groovy-json:4.0.29=testCompileClasspath,testRuntimeClasspath 14 | org.apache.groovy:groovy-xml:4.0.29=testCompileClasspath,testRuntimeClasspath 15 | org.apache.groovy:groovy:4.0.29=testCompileClasspath,testRuntimeClasspath 16 | org.apache.httpcomponents:httpclient:4.5.13=testCompileClasspath,testRuntimeClasspath 17 | org.apache.httpcomponents:httpcore:4.4.16=testCompileClasspath,testRuntimeClasspath 18 | org.apache.httpcomponents:httpmime:4.5.13=testCompileClasspath,testRuntimeClasspath 19 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 20 | org.ccil.cowan.tagsoup:tagsoup:1.2.1=testCompileClasspath,testRuntimeClasspath 21 | org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath 22 | org.junit.jupiter:junit-jupiter-api:5.14.1=testCompileClasspath,testRuntimeClasspath 23 | org.junit.jupiter:junit-jupiter-engine:5.14.1=testRuntimeClasspath 24 | org.junit.jupiter:junit-jupiter-params:5.14.1=testCompileClasspath,testRuntimeClasspath 25 | org.junit.jupiter:junit-jupiter:5.14.1=testCompileClasspath,testRuntimeClasspath 26 | org.junit.platform:junit-platform-commons:1.14.1=testCompileClasspath,testRuntimeClasspath 27 | org.junit.platform:junit-platform-engine:1.14.1=testRuntimeClasspath 28 | org.junit.platform:junit-platform-launcher:1.14.1=testRuntimeClasspath 29 | org.junit:junit-bom:5.14.1=testCompileClasspath,testRuntimeClasspath 30 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 31 | org.projectlombok:lombok:1.18.42=annotationProcessor,compileClasspath 32 | org.springframework.boot:spring-boot-dependencies:3.5.8=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 33 | org.springframework.cloud:spring-cloud-dependencies:2025.0.0=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 34 | org.springframework.data:spring-data-bom:2025.0.6=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 35 | empty=testAnnotationProcessor 36 | -------------------------------------------------------------------------------- /tealeaf-service/tealeaf-api/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | commons-codec:commons-codec:1.18.0=testCompileClasspath,testRuntimeClasspath 5 | commons-logging:commons-logging:1.2=testCompileClasspath,testRuntimeClasspath 6 | io.rest-assured:json-path:5.5.6=testCompileClasspath,testRuntimeClasspath 7 | io.rest-assured:rest-assured-common:5.5.6=testCompileClasspath,testRuntimeClasspath 8 | io.rest-assured:rest-assured:5.5.6=testCompileClasspath,testRuntimeClasspath 9 | io.rest-assured:xml-path:5.5.6=testCompileClasspath,testRuntimeClasspath 10 | jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 11 | org.apache.commons:commons-lang3:3.18.0=testCompileClasspath,testRuntimeClasspath 12 | org.apache.groovy:groovy-bom:4.0.29=testCompileClasspath,testRuntimeClasspath 13 | org.apache.groovy:groovy-json:4.0.29=testCompileClasspath,testRuntimeClasspath 14 | org.apache.groovy:groovy-xml:4.0.29=testCompileClasspath,testRuntimeClasspath 15 | org.apache.groovy:groovy:4.0.29=testCompileClasspath,testRuntimeClasspath 16 | org.apache.httpcomponents:httpclient:4.5.13=testCompileClasspath,testRuntimeClasspath 17 | org.apache.httpcomponents:httpcore:4.4.16=testCompileClasspath,testRuntimeClasspath 18 | org.apache.httpcomponents:httpmime:4.5.13=testCompileClasspath,testRuntimeClasspath 19 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 20 | org.ccil.cowan.tagsoup:tagsoup:1.2.1=testCompileClasspath,testRuntimeClasspath 21 | org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath 22 | org.junit.jupiter:junit-jupiter-api:5.14.1=testCompileClasspath,testRuntimeClasspath 23 | org.junit.jupiter:junit-jupiter-engine:5.14.1=testRuntimeClasspath 24 | org.junit.jupiter:junit-jupiter-params:5.14.1=testCompileClasspath,testRuntimeClasspath 25 | org.junit.jupiter:junit-jupiter:5.14.1=testCompileClasspath,testRuntimeClasspath 26 | org.junit.platform:junit-platform-commons:1.14.1=testCompileClasspath,testRuntimeClasspath 27 | org.junit.platform:junit-platform-engine:1.14.1=testRuntimeClasspath 28 | org.junit.platform:junit-platform-launcher:1.14.1=testRuntimeClasspath 29 | org.junit:junit-bom:5.14.1=testCompileClasspath,testRuntimeClasspath 30 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 31 | org.projectlombok:lombok:1.18.42=annotationProcessor,compileClasspath 32 | org.springframework.boot:spring-boot-dependencies:3.5.8=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 33 | org.springframework.cloud:spring-cloud-dependencies:2025.0.0=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 34 | org.springframework.data:spring-data-bom:2025.0.6=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 35 | empty=testAnnotationProcessor 36 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/error/CommonExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.error; 2 | 3 | import io.micrometer.tracing.Span; 4 | import io.micrometer.tracing.Tracer; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import org.apache.commons.lang3.exception.ExceptionUtils; 7 | 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ProblemDetail; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.bind.annotation.ExceptionHandler; 12 | import org.springframework.web.filter.ServerHttpObservationFilter; 13 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 14 | 15 | import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; 16 | import static org.springframework.http.HttpStatus.NOT_FOUND; 17 | 18 | @ControllerAdvice 19 | public class CommonExceptionHandler extends ResponseEntityExceptionHandler { 20 | private final Tracer tracer; 21 | 22 | public CommonExceptionHandler(Tracer tracer) { 23 | this.tracer = tracer; 24 | } 25 | 26 | @ExceptionHandler(ResourceNotFoundException.class) 27 | ProblemDetail onResourceNotFound(HttpServletRequest request, ResourceNotFoundException resourceNotFoundException) { 28 | return handleError(request, resourceNotFoundException, NOT_FOUND); 29 | } 30 | 31 | @ExceptionHandler(Throwable.class) 32 | ProblemDetail onThrowable(HttpServletRequest request, Throwable error) { 33 | return handleError(request, error, INTERNAL_SERVER_ERROR); 34 | } 35 | 36 | private ProblemDetail handleError(HttpServletRequest request, Throwable error, HttpStatus status) { 37 | logger.error(ExceptionUtils.getStackTrace(error)); 38 | ServerHttpObservationFilter.findObservationContext(request) 39 | .ifPresent(context -> context.setError(error)); 40 | 41 | return createProblemDetail(status, error); 42 | } 43 | 44 | private ProblemDetail createProblemDetail(HttpStatus status, Throwable error) { 45 | ProblemDetail problemDetail = ProblemDetail.forStatus(status); 46 | problemDetail.setTitle(status.getReasonPhrase()); 47 | problemDetail.setDetail(error.toString()); 48 | problemDetail.setProperty("series", status.series()); 49 | problemDetail.setProperty("rootCause", ExceptionUtils.getRootCause(error).toString()); 50 | problemDetail.setProperty("traceparent", getTraceParent()); 51 | 52 | return problemDetail; 53 | } 54 | 55 | private String getTraceParent() { 56 | Span span = tracer.currentSpan(); 57 | if (span != null) { 58 | String sampledFlag = span.context().sampled() ? "01" : "00"; 59 | return "00-%s-%s-%s".formatted(span.context().traceId(), span.context().spanId(), sampledFlag); 60 | } 61 | else { 62 | return "00-00000000000000000000000000000000-0000000000000000-00"; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/actuator/info/RuntimeInfoContributor.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.actuator.info; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.boot.SpringBootVersion; 7 | import org.springframework.boot.actuate.info.Info.Builder; 8 | import org.springframework.boot.actuate.info.InfoContributor; 9 | import org.springframework.core.SpringVersion; 10 | import org.springframework.core.env.Environment; 11 | 12 | import java.lang.management.ManagementFactory; 13 | import java.net.InetAddress; 14 | import java.time.Instant; 15 | import java.util.Map; 16 | 17 | import static java.time.Duration.between; 18 | 19 | @Slf4j 20 | @RequiredArgsConstructor 21 | public class RuntimeInfoContributor implements InfoContributor { 22 | private final Environment environment; 23 | private final Instant startTime = Instant.ofEpochMilli(ManagementFactory.getRuntimeMXBean().getStartTime()); 24 | 25 | @Override 26 | public void contribute(Builder builder) { 27 | builder.withDetail("spring", ImmutableMap.builder() 28 | .put("framework", ImmutableMap.builder().put("version", String.valueOf(SpringVersion.getVersion())).build()) 29 | .put("boot", ImmutableMap.builder().put("version", SpringBootVersion.getVersion()).build()) 30 | .build() 31 | ); 32 | 33 | builder.withDetail("environment", 34 | ImmutableMap.of("activeProfiles", environment.getActiveProfiles()) 35 | ); 36 | 37 | builder.withDetail("runtime", ImmutableMap.builder() 38 | .put("user", userInfo()) 39 | .put("network", networkInfo()) 40 | .put("startTime", startTime) 41 | .put("uptime", between(startTime, Instant.now())) 42 | .put("heartbeat", Instant.now()) 43 | .build() 44 | ); 45 | } 46 | 47 | private Map userInfo() { 48 | return ImmutableMap.builder() 49 | .put("timezone", System.getProperty("user.timezone")) 50 | .put("country", System.getProperty("user.country")) 51 | .put("language", System.getProperty("user.language")) 52 | .put("dir", System.getProperty("user.dir")) 53 | .build(); 54 | } 55 | 56 | private Map networkInfo() { 57 | return ImmutableMap.builder() 58 | .put("host", hostName()) 59 | .put("ip", ipAddress()) 60 | .build(); 61 | } 62 | 63 | private String hostName() { 64 | try { 65 | return InetAddress.getLocalHost().getHostName(); 66 | } 67 | catch (Exception exception) { 68 | log.error("Unable to fetch hostname", exception); 69 | return "n/a"; 70 | } 71 | } 72 | 73 | private String ipAddress() { 74 | try { 75 | return InetAddress.getLocalHost().getHostAddress(); 76 | } 77 | catch (Exception exception) { 78 | log.error("Unable to fetch IP", exception); 79 | return "n/a"; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | 74 | 75 | @rem Execute Gradle 76 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 77 | 78 | :end 79 | @rem End local scope for the variables with windows NT shell 80 | if %ERRORLEVEL% equ 0 goto mainEnd 81 | 82 | :fail 83 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 84 | rem the _cmd.exe /c_ return code! 85 | set EXIT_CODE=%ERRORLEVEL% 86 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 87 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 88 | exit /b %EXIT_CODE% 89 | 90 | :mainEnd 91 | if "%OS%"=="Windows_NT" endlocal 92 | 93 | :omega 94 | -------------------------------------------------------------------------------- /tea-service/src/main/resources/templates/steep.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Tea UI 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |

Let's make some Tea!

15 | 16 |
17 |
18 |
19 | 23 | 24 |
25 |
26 |
27 |
28 | 31 | 32 |
33 |
34 |
35 |
36 | 37 |
38 |
39 | 40 | 53 | 54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Teahouse 2 | 3 | ![build badge](https://github.com/jonatan-ivanov/teahouse/actions/workflows/gradle.yml/badge.svg) 4 | 5 | Demo setup for Spring Boot apps with Prometheus, Grafana, Loki, Tempo, Eureka, and Spring Boot Admin to demonstrate Observability use-cases. 6 | 7 | ## Start dependencies 8 | 9 | ```shell 10 | docker compose up 11 | ``` 12 | 13 | ## Remove logs 14 | 15 | ```shell 16 | rm -rf logs 17 | ``` 18 | 19 | ## Start the apps 20 | If you want to use an in-memory DB (H2): 21 | ```shell 22 | ./gradlew bootRun 23 | ``` 24 | 25 | If you want to use a real DB (MySQL): 26 | ```shell 27 | ./gradlew bootRun -Pprofiles=mysql 28 | ``` 29 | You need a real DB if you want to inject latency on the network (see [ToxiProxy](#useful-urls)). 30 | 31 | ## Start load tests 32 | 33 | See `SteepTeaSimulation.java` for duration, request rate, and traffic patterns. 34 | 35 | ```shell 36 | ./gradlew :load-gen:gatlingRun 37 | ``` 38 | 39 | ## Stop dependencies 40 | 41 | ```shell 42 | docker compose down 43 | ``` 44 | 45 | ## Stop dependencies and purge data 46 | 47 | ```shell 48 | docker compose down --volumes 49 | ``` 50 | 51 | ## Useful URLs 52 | 53 | - Tea UI: http://localhost:8090/steep 54 | - Tea Service: http://localhost:8090 55 | - Tealeaf Service: http://localhost:8091 56 | - Water Service: http://localhost:8092 57 | - Spring Boot Admin: http://localhost:8080 58 | - Eureka: http://localhost:8761 59 | - Prometheus: http://localhost:9090 60 | - Loki, Grafana, Tempo: http://localhost:3000 61 | - ToxiProxy UI (failure injection): http://localhost:8484 62 | - MailDev (emails for alerts): http://localhost:3001 63 | - Adminer (DB Admin UI): http://localhost:8888 (credentials: `root:password`) 64 | 65 | ## Errors simulation 66 | 67 | When start the apps for the first time, `english breakfast` is missing from the DB but you can make requests through the UI using `english breakfast` and the load generator also sends requests containing it. Those calls will end-up with HTTP 500; approximately 10% of the requests should fail: ~0.5 rq/sec error- and ~4.5 rq/sec success rate (~5 rq/sec total throughput, see `SteepTeaSimulation.java`). 68 | 69 | You should see these errors on the throughput panel of the Tea API dashboard and Grafana also alerts on them (see the emails in [MailDev](#useful-urls)). 70 | 71 | If you want to fix these errors, you need to create a record in the DB for `english breakfast`. The easiest way is sending an HTTP POST request to `/tealeaves` to create the resource (you can also log into the DB and insert the record for example using [Adminer](#useful-urls)). The `Makefile` contains a goal for this to make it simple for you, you can run this to fix errors (httpie and jq needed): 72 | 73 | ```shell 74 | make errors-fixed 75 | ``` 76 | 77 | If you want the errors back again, you need to remove the record from the DB, the `Makefile` contains a goal for this too, so you can run this to inject errors: 78 | 79 | ```shell 80 | make errors 81 | ``` 82 | 83 | ## Latency simulation 84 | 85 | If you [start the apps with the `mysql` profile](#start-the-apps), the apps are not connected to the DB directly but through [ToxiProxy](#useful-urls) so that you can inject failures (i.e.: latency) on the network. You can do this in multiple ways (e.g.: using the [ToxiProxy UI](#useful-urls) or the ToxiProxy CLI). The `Makefile` contains a goal for this to make it simple for you, you can run this to inject latency: 86 | 87 | ```shell 88 | make chaos 89 | ``` 90 | 91 | And this to eliminate the extra latency: 92 | 93 | ```shell 94 | make order 95 | ``` 96 | -------------------------------------------------------------------------------- /tealeaf-service/src/main/java/org/example/teahouse/tealeaf/controller/TealeafController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf.controller; 2 | 3 | import java.util.UUID; 4 | 5 | import io.swagger.v3.oas.annotations.Operation; 6 | import io.swagger.v3.oas.annotations.tags.Tag; 7 | import jakarta.validation.Valid; 8 | import lombok.RequiredArgsConstructor; 9 | import org.example.teahouse.core.error.ResourceNotFoundException; 10 | import org.example.teahouse.tealeaf.api.CreateTealeafRequest; 11 | import org.example.teahouse.tealeaf.api.TealeafModel; 12 | import org.example.teahouse.tealeaf.repo.Tealeaf; 13 | import org.example.teahouse.tealeaf.repo.TealeafRepository; 14 | 15 | import org.springframework.data.domain.Pageable; 16 | import org.springframework.data.web.PagedResourcesAssembler; 17 | import org.springframework.hateoas.PagedModel; 18 | import org.springframework.hateoas.server.ExposesResourceFor; 19 | import org.springframework.web.bind.annotation.DeleteMapping; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | import org.springframework.web.bind.annotation.PathVariable; 22 | import org.springframework.web.bind.annotation.PostMapping; 23 | import org.springframework.web.bind.annotation.RequestBody; 24 | import org.springframework.web.bind.annotation.RequestMapping; 25 | import org.springframework.web.bind.annotation.RequestParam; 26 | import org.springframework.web.bind.annotation.ResponseStatus; 27 | import org.springframework.web.bind.annotation.RestController; 28 | 29 | import static org.springframework.http.HttpStatus.CREATED; 30 | import static org.springframework.http.HttpStatus.NO_CONTENT; 31 | 32 | @RestController 33 | @RequiredArgsConstructor 34 | @RequestMapping("/tealeaves") 35 | @ExposesResourceFor(TealeafModel.class) 36 | @Tag(name = "Tealeaf API") 37 | public class TealeafController { 38 | private final TealeafRepository tealeafRepository; 39 | private final TealeafModelAssembler modelAssembler; 40 | private final PagedResourcesAssembler pagedAssembler; 41 | 42 | @GetMapping 43 | @Operation(summary = "Fetches all of the resources") 44 | public PagedModel findAll(Pageable pageable) { 45 | return pagedAssembler.toModel(tealeafRepository.findAll(pageable), modelAssembler); 46 | } 47 | 48 | @GetMapping("/{id}") 49 | @Operation(summary = "Fetches a resource by its ID") 50 | public TealeafModel findById(@PathVariable UUID id) { 51 | return tealeafRepository.findById(id) 52 | .map(modelAssembler::toModel) 53 | .orElseThrow(() -> new ResourceNotFoundException("tea-leaf with id: " + id)); 54 | } 55 | 56 | @GetMapping("/search/findByName") 57 | @Operation(summary = "Finds a resource by its name") 58 | public TealeafModel findByName(@RequestParam("name") String name) { 59 | return tealeafRepository.findByName(name) 60 | .map(modelAssembler::toModel) 61 | .orElseThrow(() -> new ResourceNotFoundException("tea-leaf with name: " + name)); 62 | } 63 | 64 | @PostMapping 65 | @ResponseStatus(CREATED) 66 | @Operation(summary = "Creates a resource") 67 | public TealeafModel save(@Valid @RequestBody CreateTealeafRequest createTealeafRequest) { 68 | return modelAssembler.toModel(tealeafRepository.save(Tealeaf.fromCreateTealeafRequest(createTealeafRequest))); 69 | } 70 | 71 | @DeleteMapping 72 | @ResponseStatus(NO_CONTENT) 73 | @Operation(summary = "Deletes all of the resources") 74 | public void deleteAll() { 75 | tealeafRepository.deleteAll(); 76 | } 77 | 78 | @DeleteMapping("/{id}") 79 | @ResponseStatus(NO_CONTENT) 80 | @Operation(summary = "Deletes a resource by its ID ") 81 | public void deleteById(@PathVariable UUID id) { 82 | tealeafRepository.deleteById(id); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /water-service/src/main/java/org/example/teahouse/water/controller/WaterController.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water.controller; 2 | 3 | import java.util.UUID; 4 | 5 | import io.swagger.v3.oas.annotations.Operation; 6 | import io.swagger.v3.oas.annotations.tags.Tag; 7 | import jakarta.validation.Valid; 8 | import lombok.RequiredArgsConstructor; 9 | import org.example.teahouse.core.error.ResourceNotFoundException; 10 | import org.example.teahouse.water.api.CreateWaterRequest; 11 | import org.example.teahouse.water.api.WaterModel; 12 | import org.example.teahouse.water.repo.Water; 13 | import org.example.teahouse.water.repo.WaterRepository; 14 | 15 | import org.springframework.data.domain.Pageable; 16 | import org.springframework.data.web.PagedResourcesAssembler; 17 | import org.springframework.hateoas.PagedModel; 18 | import org.springframework.hateoas.server.ExposesResourceFor; 19 | import org.springframework.web.bind.annotation.DeleteMapping; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | import org.springframework.web.bind.annotation.PathVariable; 22 | import org.springframework.web.bind.annotation.PostMapping; 23 | import org.springframework.web.bind.annotation.RequestBody; 24 | import org.springframework.web.bind.annotation.RequestMapping; 25 | import org.springframework.web.bind.annotation.RequestParam; 26 | import org.springframework.web.bind.annotation.ResponseStatus; 27 | import org.springframework.web.bind.annotation.RestController; 28 | import org.springframework.web.server.ResponseStatusException; 29 | 30 | import static org.springframework.http.HttpStatus.CREATED; 31 | import static org.springframework.http.HttpStatus.NOT_FOUND; 32 | import static org.springframework.http.HttpStatus.NO_CONTENT; 33 | 34 | @RestController 35 | @RequestMapping("/waters") 36 | @ExposesResourceFor(WaterModel.class) 37 | @RequiredArgsConstructor 38 | @Tag(name = "Water API") 39 | public class WaterController { 40 | private final WaterRepository waterRepository; 41 | private final WaterModelAssembler modelAssembler; 42 | private final PagedResourcesAssembler pagedAssembler; 43 | 44 | @GetMapping 45 | @Operation(summary = "Fetches all of the resources") 46 | public PagedModel findAll(Pageable pageable) { 47 | return pagedAssembler.toModel(waterRepository.findAll(pageable), modelAssembler); 48 | } 49 | 50 | @GetMapping("/{id}") 51 | @Operation(summary = "Fetches a resource by its ID") 52 | public WaterModel findById(@PathVariable UUID id) { 53 | return waterRepository.findById(id) 54 | .map(modelAssembler::toModel) 55 | .orElseThrow(() -> new ResourceNotFoundException("water with id: " + id)); 56 | } 57 | 58 | @GetMapping("/search/findBySize") 59 | @Operation(summary = "Finds a resource by its size") 60 | public WaterModel findBySize(@RequestParam("size") String size) { 61 | return waterRepository.findBySize(size) 62 | .map(modelAssembler::toModel) 63 | .orElseThrow(() -> new ResourceNotFoundException("water with size: " + size)); 64 | } 65 | 66 | @PostMapping 67 | @ResponseStatus(CREATED) 68 | @Operation(summary = "Creates a resource") 69 | public WaterModel save(@Valid @RequestBody CreateWaterRequest createWaterRequest) { 70 | return modelAssembler.toModel(waterRepository.save(Water.fromCreateWaterRequest(createWaterRequest))); 71 | } 72 | 73 | @DeleteMapping 74 | @ResponseStatus(NO_CONTENT) 75 | @Operation(summary = "Deletes all of the resources") 76 | public void deleteAll() { 77 | waterRepository.deleteAll(); 78 | } 79 | 80 | @DeleteMapping("/{id}") 81 | @ResponseStatus(NO_CONTENT) 82 | @Operation(summary = "Deletes a resource by its ID ") 83 | public void deleteById(@PathVariable UUID id) { 84 | waterRepository.deleteById(id); 85 | } 86 | 87 | private ResponseStatusException notFound() { 88 | return new ResponseStatusException(NOT_FOUND, "Resource not found"); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /teahouse.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "e7552ad3-079b-424b-973c-6a2e92c5ecf2", 4 | "name": "teahouse", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", 6 | "_exporter_id": "13782682" 7 | }, 8 | "item": [ 9 | { 10 | "name": "/tea/sencha?size=small", 11 | "request": { 12 | "method": "GET", 13 | "header": [], 14 | "url": { 15 | "raw": "http://localhost:8090/tea/sencha?size=small", 16 | "protocol": "http", 17 | "host": [ 18 | "localhost" 19 | ], 20 | "port": "8090", 21 | "path": [ 22 | "tea", 23 | "sencha" 24 | ], 25 | "query": [ 26 | { 27 | "key": "size", 28 | "value": "small" 29 | } 30 | ] 31 | } 32 | }, 33 | "response": [] 34 | }, 35 | { 36 | "name": "tea-service/actuator", 37 | "request": { 38 | "method": "GET", 39 | "header": [], 40 | "url": { 41 | "raw": "http://localhost:8090/actuator", 42 | "protocol": "http", 43 | "host": [ 44 | "localhost" 45 | ], 46 | "port": "8090", 47 | "path": [ 48 | "actuator" 49 | ] 50 | } 51 | }, 52 | "response": [] 53 | }, 54 | { 55 | "name": "/tealeaves", 56 | "request": { 57 | "method": "GET", 58 | "header": [], 59 | "url": { 60 | "raw": "http://localhost:8092/tealeaves", 61 | "protocol": "http", 62 | "host": [ 63 | "localhost" 64 | ], 65 | "port": "8092", 66 | "path": [ 67 | "tealeaves" 68 | ] 69 | } 70 | }, 71 | "response": [] 72 | }, 73 | { 74 | "name": "/tealeaves", 75 | "request": { 76 | "method": "POST", 77 | "header": [], 78 | "body": { 79 | "mode": "raw", 80 | "raw": "{\n \"name\": \"english breakfast\",\n \"type\": \"black\",\n \"suggestedAmount\": \"5 g\",\n \"suggestedWaterTemperature\": \"99 °C\",\n \"suggestedSteepingTime\": \"3 min\"\n}", 81 | "options": { 82 | "raw": { 83 | "language": "json" 84 | } 85 | } 86 | }, 87 | "url": { 88 | "raw": "http://localhost:8092/tealeaves", 89 | "protocol": "http", 90 | "host": [ 91 | "localhost" 92 | ], 93 | "port": "8092", 94 | "path": [ 95 | "tealeaves" 96 | ] 97 | } 98 | }, 99 | "response": [] 100 | }, 101 | { 102 | "name": "tealeaf-service/actuator", 103 | "request": { 104 | "method": "GET", 105 | "header": [], 106 | "url": { 107 | "raw": "http://localhost:8092/actuator", 108 | "protocol": "http", 109 | "host": [ 110 | "localhost" 111 | ], 112 | "port": "8092", 113 | "path": [ 114 | "actuator" 115 | ] 116 | } 117 | }, 118 | "response": [] 119 | }, 120 | { 121 | "name": "/waters", 122 | "request": { 123 | "method": "GET", 124 | "header": [], 125 | "url": { 126 | "raw": "http://localhost:8091/waters", 127 | "protocol": "http", 128 | "host": [ 129 | "localhost" 130 | ], 131 | "port": "8091", 132 | "path": [ 133 | "waters" 134 | ] 135 | } 136 | }, 137 | "response": [] 138 | }, 139 | { 140 | "name": "/waters", 141 | "request": { 142 | "method": "POST", 143 | "header": [], 144 | "body": { 145 | "mode": "raw", 146 | "raw": "{\n \"amount\": \"400 ml\",\n \"size\": \"xlarge\"\n}\n", 147 | "options": { 148 | "raw": { 149 | "language": "json" 150 | } 151 | } 152 | }, 153 | "url": { 154 | "raw": "http://localhost:8091/waters", 155 | "protocol": "http", 156 | "host": [ 157 | "localhost" 158 | ], 159 | "port": "8091", 160 | "path": [ 161 | "waters" 162 | ] 163 | } 164 | }, 165 | "response": [] 166 | }, 167 | { 168 | "name": "water-service/actuator", 169 | "request": { 170 | "method": "GET", 171 | "header": [], 172 | "url": { 173 | "raw": "http://localhost:8091/actuator", 174 | "protocol": "http", 175 | "host": [ 176 | "localhost" 177 | ], 178 | "port": "8091", 179 | "path": [ 180 | "actuator" 181 | ] 182 | } 183 | }, 184 | "response": [] 185 | } 186 | ] 187 | } -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/actuator/config/CommonActuatorConfig.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.actuator.config; 2 | 3 | import feign.micrometer.FeignContext; 4 | import io.micrometer.common.KeyValue; 5 | import io.micrometer.observation.Observation; 6 | import io.micrometer.observation.ObservationFilter; 7 | import io.micrometer.observation.ObservationPredicate; 8 | import net.ttddyy.observation.tracing.DataSourceBaseContext; 9 | import org.example.teahouse.core.actuator.info.RuntimeInfoContributor; 10 | 11 | import org.springframework.boot.actuate.info.InfoContributor; 12 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.core.env.Environment; 16 | import org.springframework.http.server.observation.ServerRequestObservationContext; 17 | import org.springframework.web.context.request.RequestAttributes; 18 | import org.springframework.web.context.request.RequestContextHolder; 19 | import org.springframework.web.context.request.ServletRequestAttributes; 20 | import org.springframework.web.filter.ServerHttpObservationFilter; 21 | 22 | import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST; 23 | 24 | @Configuration(proxyBeanMethods = false) 25 | public class CommonActuatorConfig { 26 | @Bean 27 | InfoContributor runtimeInfoContributor(Environment environment) { 28 | return new RuntimeInfoContributor(environment); 29 | } 30 | 31 | @Bean 32 | ObservationPredicate noActuatorServerObservations() { 33 | return (name, context) -> { 34 | if (name.equals("http.server.requests") && context instanceof ServerRequestObservationContext serverContext) { 35 | return !serverContext.getCarrier().getRequestURI().startsWith("/actuator"); 36 | } 37 | else { 38 | return true; 39 | } 40 | }; 41 | } 42 | 43 | @Bean 44 | ObservationPredicate noActuatorClientObservations() { 45 | return (name, context) -> { 46 | if (name.equals("http.client.requests") && context instanceof FeignContext feignContext) { 47 | return !feignContext.getCarrier().url().endsWith("/actuator/health"); 48 | } 49 | else { 50 | return true; 51 | } 52 | }; 53 | } 54 | 55 | @Bean 56 | ObservationPredicate noRootlessHttpObservations() { 57 | return (name, context) -> { 58 | RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 59 | if (requestAttributes instanceof ServletRequestAttributes) { 60 | Observation observation = (Observation) requestAttributes.getAttribute(ServerHttpObservationFilter.class.getName() + ".observation", SCOPE_REQUEST); 61 | return observation == null || !observation.isNoop(); 62 | } 63 | else { 64 | return true; 65 | } 66 | }; 67 | } 68 | 69 | @Bean 70 | ObservationFilter tempoErrorFilter() { 71 | // TODO: remove this once Tempo is fixed: https://github.com/grafana/tempo/issues/1916 72 | return context -> { 73 | if (context.getError() != null) { 74 | context.addHighCardinalityKeyValue(KeyValue.of("error", "true")); 75 | context.addHighCardinalityKeyValue(KeyValue.of("errorMessage", context.getError().getMessage())); 76 | } 77 | return context; 78 | }; 79 | } 80 | 81 | @Configuration(proxyBeanMethods = false) 82 | @ConditionalOnClass(DataSourceBaseContext.class) 83 | static class DataSourceActuatorConfig { 84 | @Bean 85 | ObservationFilter tempoServiceGraphFilter() { 86 | // TODO: remove this once Tempo is fixed: https://github.com/grafana/tempo/issues/2212 87 | return context -> { 88 | if (context instanceof DataSourceBaseContext dataSourceContext && dataSourceContext.getRemoteServiceName() != null) { 89 | context.addHighCardinalityKeyValue(KeyValue.of("db.name", dataSourceContext.getRemoteServiceName())); 90 | } 91 | return context; 92 | }; 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /core/src/main/java/org/example/teahouse/core/observation/AbstractMidiObservationHandler.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.core.observation; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.CompletableFuture; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.LinkedBlockingQueue; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import javax.sound.midi.MidiChannel; 11 | import javax.sound.midi.MidiSystem; 12 | import javax.sound.midi.MidiUnavailableException; 13 | import javax.sound.midi.Synthesizer; 14 | 15 | import io.micrometer.core.instrument.Gauge; 16 | import io.micrometer.core.instrument.MeterRegistry; 17 | import io.micrometer.observation.Observation; 18 | import io.micrometer.observation.ObservationHandler; 19 | import jakarta.annotation.Nonnull; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | import org.springframework.beans.factory.DisposableBean; 24 | 25 | public abstract class AbstractMidiObservationHandler implements ObservationHandler, DisposableBean { 26 | 27 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 28 | 29 | private final String startTimeKey = this.getClass().getName(); 30 | 31 | ExecutorService executorService; 32 | 33 | private final BlockingQueue queue; 34 | 35 | protected final Synthesizer synthesizer; 36 | 37 | protected AbstractMidiObservationHandler(MeterRegistry registry) throws MidiUnavailableException { 38 | this(registry, 2); 39 | } 40 | 41 | protected AbstractMidiObservationHandler(MeterRegistry registry, int nThreads) throws MidiUnavailableException { 42 | this.synthesizer = MidiSystem.getSynthesizer(); 43 | this.synthesizer.open(); 44 | this.queue = new LinkedBlockingQueue<>(100); 45 | this.executorService = Executors.newFixedThreadPool(nThreads); 46 | for (int i = 0; i < nThreads; i++) { 47 | CompletableFuture.runAsync(this::processQueue, executorService); 48 | } 49 | Gauge.builder("midi.queue.size", this.queue::size).tag("handler", this.getClass().getSimpleName()).register(registry); 50 | Gauge.builder("midi.queue.remaining", this.queue::remainingCapacity).tag("handler", this.getClass().getSimpleName()).register(registry); 51 | } 52 | 53 | public record Note(@Nonnull MidiChannel channel, int noteNumber, int velocity, long duration) {} 54 | 55 | @Nonnull 56 | protected abstract Note contextToNote(@Nonnull T context); 57 | 58 | @Override 59 | public void onStart(@Nonnull T context) { 60 | context.put(this.startTimeKey, System.nanoTime()); 61 | } 62 | 63 | @Override 64 | public void onStop(@Nonnull T context) { 65 | try { 66 | if (this.queue.remainingCapacity() < 1) { 67 | this.queue.poll(); 68 | } 69 | this.queue.put(contextToNote(context)); 70 | } 71 | catch (InterruptedException e) { 72 | this.logger.warn("Unable to schedule note to play", e); 73 | } 74 | } 75 | 76 | @Override 77 | public void destroy() { 78 | this.executorService.shutdownNow(); 79 | this.synthesizer.close(); 80 | } 81 | 82 | protected int randomNote(@Nonnull int[] notes) { 83 | return notes[(int)(Math.random() * notes.length)]; 84 | } 85 | 86 | protected int randomNote(int beginInclusive, int endExclusive) { 87 | return (int)(Math.random() * (endExclusive - beginInclusive)) + beginInclusive; 88 | } 89 | 90 | protected long duration(@Nonnull Observation.Context context) { 91 | @SuppressWarnings("DataFlowIssue") 92 | long nanos = System.nanoTime() - context.get(this.startTimeKey); 93 | return Math.max(100, TimeUnit.NANOSECONDS.toMillis(nanos)); 94 | } 95 | 96 | @SuppressWarnings("InfiniteLoopStatement") 97 | private void processQueue() { 98 | try { 99 | while (true) { 100 | Note note = this.queue.take(); 101 | note.channel().noteOn(note.noteNumber(), note.velocity()); 102 | sleep(note.duration()); 103 | note.channel().noteOff(note.noteNumber()); 104 | } 105 | } 106 | catch (InterruptedException e) { 107 | this.logger.warn("Unable to fetch note to play", e); 108 | } 109 | } 110 | 111 | private void sleep(long duration) { 112 | try { 113 | Thread.sleep(duration); 114 | } 115 | catch (InterruptedException e) { 116 | this.logger.warn("Playing note was interrupted", e); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | mysql: 3 | container_name: mysql 4 | image: mysql:9.3.0 # https://hub.docker.com/_/mysql 5 | extra_hosts: ['host.docker.internal:host-gateway'] 6 | environment: 7 | MYSQL_ROOT_PASSWORD: password 8 | volumes: 9 | - mysql:/var/lib/mysql 10 | - ./docker/mysql/initdb:/docker-entrypoint-initdb.d 11 | ports: 12 | - "3306:3306" 13 | adminer: 14 | container_name: adminer 15 | image: adminer:5.3.0-standalone # https://hub.docker.com/_/adminer 16 | extra_hosts: ['host.docker.internal:host-gateway'] 17 | environment: 18 | ADMINER_DEFAULT_SERVER: mysql 19 | depends_on: 20 | - mysql 21 | ports: 22 | - "8888:8080" 23 | toxiproxy: 24 | container_name: toxiproxy 25 | image: ghcr.io/shopify/toxiproxy:2.12.0 # https://github.com/shopify/toxiproxy/pkgs/container/toxiproxy 26 | extra_hosts: ['host.docker.internal:host-gateway'] 27 | command: -host=0.0.0.0 -config /config/toxiproxy.json -proxy-metrics -runtime-metrics 28 | depends_on: 29 | - mysql 30 | volumes: 31 | - ./docker/toxiproxy:/config 32 | ports: 33 | - "8474:8474" 34 | - "3307:3307" 35 | - "3308:3308" 36 | toxiproxy-ui: 37 | container_name: toxiproxy-ui 38 | image: buckle/toxiproxy-frontend:0.10 # https://hub.docker.com/r/buckle/toxiproxy-frontend 39 | extra_hosts: ['host.docker.internal:host-gateway'] 40 | environment: 41 | - TOXIPROXY_URL=http://host.docker.internal:8474 42 | - SPRING_AUTOCONFIGURE_EXCLUDE=org.springframework.boot.actuate.autoconfigure.metrics.SystemMetricsAutoConfiguration,org.springframework.boot.actuate.autoconfigure.metrics.web.tomcat.TomcatMetricsAutoConfiguration 43 | depends_on: 44 | - toxiproxy 45 | ports: 46 | - "8484:8080" 47 | prometheus: 48 | container_name: prometheus 49 | image: prom/prometheus:v3.5.0 # https://hub.docker.com/r/prom/prometheus 50 | extra_hosts: ['host.docker.internal:host-gateway'] 51 | command: 52 | - --enable-feature=exemplar-storage 53 | - --web.enable-remote-write-receiver 54 | - --config.file=/etc/prometheus/prometheus.yml 55 | volumes: 56 | - prometheus:/prometheus 57 | - ./docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro 58 | ports: 59 | - "9090:9090" 60 | grafana: 61 | container_name: grafana 62 | image: grafana/grafana:12.0.2 # https://hub.docker.com/r/grafana/grafana/tags and https://github.com/grafana/grafana/releases 63 | extra_hosts: ['host.docker.internal:host-gateway'] 64 | environment: 65 | - GF_AUTH_ANONYMOUS_ENABLED=true 66 | - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin 67 | - GF_AUTH_DISABLE_LOGIN_FORM=true 68 | volumes: 69 | - ./docker/grafana/grafana.ini:/etc/grafana/grafana.ini:ro 70 | - ./docker/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro 71 | - ./docker/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro 72 | - ./docker/grafana/provisioning/alerting:/etc/grafana/provisioning/alerting:ro 73 | ports: 74 | - "3000:3000" 75 | tempo-init: 76 | # Tempo runs as user 10001, and docker compose creates the volume as root. 77 | # As such, we need to chown the volume in order for Tempo to start correctly. 78 | # This should not be needed but this is the official solution recommended by Tempo maintainers 79 | # See: https://github.com/grafana/tempo/blob/a21001a72a5865bfcfc1b0d2dfa30160c5a26103/example/docker-compose/local/docker-compose.yaml 80 | # See: https://github.com/grafana/tempo/issues/1657 81 | image: &tempoImage grafana/tempo:2.8.1 # https://hub.docker.com/r/grafana/tempo/tags and https://github.com/grafana/tempo/releases 82 | user: root 83 | entrypoint: 84 | - "chown" 85 | - "10001:10001" 86 | - "/var/tempo" 87 | volumes: 88 | - tempo:/var/tempo 89 | tempo: 90 | container_name: tempo 91 | image: *tempoImage 92 | extra_hosts: ['host.docker.internal:host-gateway'] 93 | command: ['-config.file=/etc/tempo.yml'] 94 | depends_on: ['tempo-init'] 95 | volumes: 96 | - tempo:/var/tempo 97 | - ./docker/grafana/tempo.yml:/etc/tempo.yml:ro 98 | ports: 99 | - "3200:3200" # tempo 100 | - "9411:9411" # zipkin 101 | loki: 102 | container_name: loki 103 | image: grafana/loki:3.4.5 # https://hub.docker.com/r/grafana/loki/tags and https://github.com/grafana/loki/releases 104 | extra_hosts: ['host.docker.internal:host-gateway'] 105 | command: ['-config.file=/etc/loki/local-config.yaml'] 106 | ports: 107 | - "3100:3100" 108 | maildev: 109 | container_name: maildev 110 | image: maildev/maildev:2.2.1 # https://hub.docker.com/r/maildev/maildev/tags 111 | extra_hosts: [ 'host.docker.internal:host-gateway' ] 112 | ports: 113 | - "3001:1080" 114 | - "25:1025" 115 | volumes: 116 | mysql: 117 | driver: local 118 | prometheus: 119 | driver: local 120 | tempo: 121 | driver: local 122 | -------------------------------------------------------------------------------- /water-service/src/test/java/org/example/teahouse/water/WaterServiceApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.water; 2 | 3 | import org.example.teahouse.water.api.CreateWaterRequest; 4 | import org.flywaydb.core.Flyway; 5 | import org.junit.jupiter.api.AfterEach; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.web.server.LocalServerPort; 13 | import org.springframework.test.context.ActiveProfiles; 14 | 15 | import static io.restassured.RestAssured.given; 16 | import static io.restassured.http.ContentType.JSON; 17 | import static org.hamcrest.Matchers.blankOrNullString; 18 | import static org.hamcrest.Matchers.equalTo; 19 | import static org.hamcrest.Matchers.not; 20 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 21 | 22 | @ActiveProfiles("test") 23 | @SpringBootTest(webEnvironment = RANDOM_PORT) 24 | class WaterServiceApplicationTest { 25 | @LocalServerPort int port; 26 | 27 | @AfterEach 28 | void cleanDb(@Autowired Flyway flyway) { 29 | flyway.clean(); 30 | flyway.migrate(); 31 | } 32 | 33 | @Test 34 | void watersEndpointShouldReturnWaterResources() { 35 | given() 36 | .port(this.port) 37 | .accept(JSON) 38 | .when() 39 | .get("/waters") 40 | .then() 41 | .statusCode(200) 42 | .body("page.totalElements", equalTo(3)) 43 | .body("_embedded.waters.size()", equalTo(3)) 44 | .rootPath("_embedded.waters.find { it.size == 'small' }") 45 | .body("id", equalTo("dd1457d5-e0ec-4ba8-aaf5-b880e5aee672")) 46 | .body("size", equalTo("small")) 47 | .body("amount", equalTo("100 ml")) 48 | .detachRootPath("") 49 | .rootPath("_embedded.waters.find { it.size == 'medium' }") 50 | .body("id", equalTo("768805a0-3ef7-478f-8de4-6c3ed1bcf65b")) 51 | .body("size", equalTo("medium")) 52 | .body("amount", equalTo("200 ml")) 53 | .detachRootPath("") 54 | .rootPath("_embedded.waters.find { it.size == 'large' }") 55 | .body("id", equalTo("71d27ee9-8146-411a-b87c-289aa198d881")) 56 | .body("size", equalTo("large")) 57 | .body("amount", equalTo("300 ml")); 58 | } 59 | 60 | @ParameterizedTest 61 | @CsvSource({ 62 | "dd1457d5-e0ec-4ba8-aaf5-b880e5aee672,small,100 ml", 63 | "768805a0-3ef7-478f-8de4-6c3ed1bcf65b,medium,200 ml", 64 | "71d27ee9-8146-411a-b87c-289aa198d881,large,300 ml" 65 | }) 66 | void watersEndpointShouldReturnWaterResourceById(String id, String size, String amount) { 67 | given() 68 | .port(this.port) 69 | .accept(JSON) 70 | .when() 71 | .get("/waters/" + id) 72 | .then() 73 | .statusCode(200) 74 | .body("id", equalTo(id)) 75 | .body("size", equalTo(size)) 76 | .body("amount", equalTo(amount)); 77 | } 78 | 79 | @ParameterizedTest 80 | @CsvSource({ 81 | "dd1457d5-e0ec-4ba8-aaf5-b880e5aee672,small,100 ml", 82 | "768805a0-3ef7-478f-8de4-6c3ed1bcf65b,medium,200 ml", 83 | "71d27ee9-8146-411a-b87c-289aa198d881,large,300 ml" 84 | }) 85 | void searchEndpointShouldFindWaterResources(String id, String size, String amount) { 86 | given() 87 | .port(this.port) 88 | .accept(JSON) 89 | .param("size", size) 90 | .when() 91 | .get("/waters/search/findBySize") 92 | .then() 93 | .statusCode(200) 94 | .body("id", equalTo(id)) 95 | .body("size", equalTo(size)) 96 | .body("amount", equalTo(amount)); 97 | } 98 | 99 | @Test 100 | void watersEndpointShouldSupportCreateAndDelete() { 101 | given() 102 | .port(this.port) 103 | .accept(JSON) 104 | .when() 105 | .get("/waters") 106 | .then() 107 | .statusCode(200) 108 | .body("page.totalElements", equalTo(3)); 109 | 110 | given() 111 | .port(this.port) 112 | .accept(JSON) 113 | .when() 114 | .delete("/waters") 115 | .then() 116 | .statusCode(204); 117 | 118 | given() 119 | .port(this.port) 120 | .accept(JSON) 121 | .when() 122 | .get("/waters") 123 | .then() 124 | .statusCode(200) 125 | .body("page.totalElements", equalTo(0)); 126 | 127 | String id = given() 128 | .port(this.port) 129 | .accept(JSON) 130 | .contentType(JSON) 131 | .body(new CreateWaterRequest("xxl", "500 ml")) 132 | .when() 133 | .post("/waters") 134 | .then() 135 | .statusCode(201) 136 | .body("id", not(blankOrNullString())) 137 | .body("size", equalTo("xxl")) 138 | .body("amount", equalTo("500 ml")) 139 | .extract().body().path("id"); 140 | 141 | given() 142 | .port(this.port) 143 | .accept(JSON) 144 | .when() 145 | .get("/waters") 146 | .then() 147 | .statusCode(200) 148 | .body("_embedded.waters.size()", equalTo(1)) 149 | .rootPath("_embedded.waters[0]") 150 | .body("id", equalTo(id)) 151 | .body("size", equalTo("xxl")) 152 | .body("amount", equalTo("500 ml")); 153 | 154 | given() 155 | .port(this.port) 156 | .accept(JSON) 157 | .when() 158 | .get("/waters/" + id) 159 | .then() 160 | .statusCode(200) 161 | .body("id", equalTo(id)) 162 | .body("size", equalTo("xxl")) 163 | .body("amount", equalTo("500 ml")); 164 | 165 | given() 166 | .port(this.port) 167 | .accept(JSON) 168 | .when() 169 | .delete("/waters/" + id) 170 | .then() 171 | .statusCode(204); 172 | 173 | given() 174 | .port(this.port) 175 | .accept(JSON) 176 | .when() 177 | .get("/waters") 178 | .then() 179 | .statusCode(200) 180 | .body("page.totalElements", equalTo(0)); 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /core/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | aopalliance:aopalliance:1.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 5 | ch.qos.logback.access:logback-access-common:2.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 6 | ch.qos.logback.access:logback-access-tomcat:2.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 7 | ch.qos.logback:logback-core:1.5.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 8 | com.fasterxml.jackson.core:jackson-annotations:2.19.4=runtimeClasspath,testRuntimeClasspath 9 | com.fasterxml.jackson.core:jackson-core:2.19.4=runtimeClasspath,testRuntimeClasspath 10 | com.fasterxml.jackson.core:jackson-databind:2.19.4=runtimeClasspath,testRuntimeClasspath 11 | com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.19.4=runtimeClasspath,testRuntimeClasspath 12 | com.fasterxml.jackson:jackson-bom:2.19.4=runtimeClasspath,testRuntimeClasspath 13 | com.google.errorprone:error_prone_annotations:2.41.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 14 | com.google.guava:failureaccess:1.0.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 15 | com.google.guava:guava:33.5.0-jre=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 16 | com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 17 | com.google.j2objc:j2objc-annotations:3.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 18 | commons-codec:commons-codec:1.18.0=testCompileClasspath,testRuntimeClasspath 19 | commons-logging:commons-logging:1.2=testCompileClasspath,testRuntimeClasspath 20 | io.github.openfeign:feign-core:13.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 21 | io.github.openfeign:feign-micrometer:13.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 22 | io.micrometer:context-propagation:1.1.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 23 | io.micrometer:micrometer-commons:1.15.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 24 | io.micrometer:micrometer-core:1.15.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 25 | io.micrometer:micrometer-observation:1.15.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 26 | io.micrometer:micrometer-tracing:1.5.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 27 | io.rest-assured:json-path:5.5.6=testCompileClasspath,testRuntimeClasspath 28 | io.rest-assured:rest-assured-common:5.5.6=testCompileClasspath,testRuntimeClasspath 29 | io.rest-assured:rest-assured:5.5.6=testCompileClasspath,testRuntimeClasspath 30 | io.rest-assured:xml-path:5.5.6=testCompileClasspath,testRuntimeClasspath 31 | net.ttddyy.observation:datasource-micrometer-spring-boot:1.2.0=compileClasspath 32 | net.ttddyy.observation:datasource-micrometer:1.2.0=compileClasspath 33 | net.ttddyy:datasource-proxy:1.11.0=compileClasspath 34 | org.apache.commons:commons-lang3:3.17.0=compileClasspath,runtimeClasspath 35 | org.apache.commons:commons-lang3:3.18.0=testCompileClasspath,testRuntimeClasspath 36 | org.apache.groovy:groovy-bom:4.0.29=testCompileClasspath,testRuntimeClasspath 37 | org.apache.groovy:groovy-json:4.0.29=testCompileClasspath,testRuntimeClasspath 38 | org.apache.groovy:groovy-xml:4.0.29=testCompileClasspath,testRuntimeClasspath 39 | org.apache.groovy:groovy:4.0.29=testCompileClasspath,testRuntimeClasspath 40 | org.apache.httpcomponents:httpclient:4.5.13=testCompileClasspath,testRuntimeClasspath 41 | org.apache.httpcomponents:httpcore:4.4.16=testCompileClasspath,testRuntimeClasspath 42 | org.apache.httpcomponents:httpmime:4.5.13=testCompileClasspath,testRuntimeClasspath 43 | org.apache.tomcat.embed:tomcat-embed-core:10.1.49=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 44 | org.apache.tomcat:tomcat-annotations-api:10.1.49=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 45 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 46 | org.ccil.cowan.tagsoup:tagsoup:1.2.1=testCompileClasspath,testRuntimeClasspath 47 | org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath 48 | org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath 49 | org.jspecify:jspecify:1.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 50 | org.junit.jupiter:junit-jupiter-api:5.14.1=testCompileClasspath,testRuntimeClasspath 51 | org.junit.jupiter:junit-jupiter-engine:5.14.1=testRuntimeClasspath 52 | org.junit.jupiter:junit-jupiter-params:5.14.1=testCompileClasspath,testRuntimeClasspath 53 | org.junit.jupiter:junit-jupiter:5.14.1=testCompileClasspath,testRuntimeClasspath 54 | org.junit.platform:junit-platform-commons:1.14.1=testCompileClasspath,testRuntimeClasspath 55 | org.junit.platform:junit-platform-engine:1.14.1=testRuntimeClasspath 56 | org.junit.platform:junit-platform-launcher:1.14.1=testRuntimeClasspath 57 | org.junit:junit-bom:5.14.1=testCompileClasspath,testRuntimeClasspath 58 | org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath 59 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 60 | org.projectlombok:lombok:1.18.42=annotationProcessor,compileClasspath 61 | org.slf4j:slf4j-api:2.0.17=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 62 | org.springframework.boot:spring-boot-actuator-autoconfigure:3.5.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 63 | org.springframework.boot:spring-boot-actuator:3.5.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 64 | org.springframework.boot:spring-boot-autoconfigure:3.5.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 65 | org.springframework.boot:spring-boot-dependencies:3.5.8=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 66 | org.springframework.boot:spring-boot:3.5.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 67 | org.springframework.cloud:spring-cloud-dependencies:2025.0.0=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 68 | org.springframework.data:spring-data-bom:2025.0.6=annotationProcessor,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 69 | org.springframework:spring-aop:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 70 | org.springframework:spring-beans:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 71 | org.springframework:spring-context:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 72 | org.springframework:spring-core:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 73 | org.springframework:spring-expression:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 74 | org.springframework:spring-jcl:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 75 | org.springframework:spring-web:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 76 | org.springframework:spring-webmvc:6.2.14=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 77 | empty=testAnnotationProcessor 78 | -------------------------------------------------------------------------------- /docker/grafana/provisioning/alerting/alerts.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | groups: 3 | - orgId: 1 4 | name: 10s 5 | folder: Teahouse 6 | interval: 10s 7 | rules: 8 | - uid: dce655bc-f9d5-41fa-bec3-53ce55a1e049 9 | title: High Error Rate 10 | condition: C 11 | data: 12 | - refId: A 13 | relativeTimeRange: 14 | from: 60 15 | to: 0 16 | datasourceUid: prometheus 17 | model: 18 | datasource: 19 | type: prometheus 20 | uid: prometheus 21 | editorMode: code 22 | exemplar: false 23 | expr: rate(http_server_requests_seconds_count{outcome!="SUCCESS", application="tea-service"}[$__rate_interval]) 24 | hide: false 25 | instant: false 26 | intervalMs: 1000 27 | maxDataPoints: 43200 28 | range: true 29 | refId: A 30 | - refId: B 31 | relativeTimeRange: 32 | from: 60 33 | to: 0 34 | datasourceUid: __expr__ 35 | model: 36 | conditions: 37 | - evaluator: 38 | params: [] 39 | type: gt 40 | operator: 41 | type: and 42 | query: 43 | params: 44 | - B 45 | reducer: 46 | params: [] 47 | type: last 48 | type: query 49 | datasource: 50 | type: __expr__ 51 | uid: __expr__ 52 | expression: A 53 | hide: false 54 | intervalMs: 1000 55 | maxDataPoints: 43200 56 | reducer: last 57 | refId: B 58 | settings: 59 | mode: dropNN 60 | type: reduce 61 | - refId: C 62 | relativeTimeRange: 63 | from: 60 64 | to: 0 65 | datasourceUid: __expr__ 66 | model: 67 | conditions: 68 | - evaluator: 69 | params: 70 | - 0.1 71 | type: gt 72 | operator: 73 | type: and 74 | query: 75 | params: 76 | - C 77 | reducer: 78 | params: [] 79 | type: last 80 | type: query 81 | datasource: 82 | type: __expr__ 83 | uid: __expr__ 84 | expression: B 85 | hide: false 86 | intervalMs: 1000 87 | maxDataPoints: 43200 88 | refId: C 89 | type: threshold 90 | dashboardUid: 280lKAr7k 91 | panelId: 8 92 | noDataState: OK 93 | execErrState: Error 94 | for: 10s 95 | annotations: 96 | __dashboardUid__: 280lKAr7k 97 | __panelId__: "8" 98 | summary: Error rate is high 99 | isPaused: false 100 | - uid: d4ac5559-95ec-4295-819f-a9777ae51518 101 | title: High Latency 102 | condition: C 103 | data: 104 | - refId: A 105 | relativeTimeRange: 106 | from: 60 107 | to: 0 108 | datasourceUid: prometheus 109 | model: 110 | datasource: 111 | type: prometheus 112 | uid: prometheus 113 | editorMode: code 114 | expr: histogram_quantile(1.00, sum(rate(http_server_requests_seconds_bucket{application=~"tea-service"}[$__rate_interval])) by (le)) 115 | hide: false 116 | instant: false 117 | intervalMs: 1000 118 | maxDataPoints: 43200 119 | range: true 120 | refId: A 121 | - refId: B 122 | relativeTimeRange: 123 | from: 60 124 | to: 0 125 | datasourceUid: __expr__ 126 | model: 127 | conditions: 128 | - evaluator: 129 | params: [] 130 | type: gt 131 | operator: 132 | type: and 133 | query: 134 | params: 135 | - B 136 | reducer: 137 | params: [] 138 | type: last 139 | type: query 140 | datasource: 141 | type: __expr__ 142 | uid: __expr__ 143 | expression: A 144 | hide: false 145 | intervalMs: 1000 146 | maxDataPoints: 43200 147 | reducer: last 148 | refId: B 149 | settings: 150 | mode: dropNN 151 | type: reduce 152 | - refId: C 153 | relativeTimeRange: 154 | from: 60 155 | to: 0 156 | datasourceUid: __expr__ 157 | model: 158 | conditions: 159 | - evaluator: 160 | params: 161 | - 0.1 162 | type: gt 163 | operator: 164 | type: and 165 | query: 166 | params: 167 | - C 168 | reducer: 169 | params: [] 170 | type: last 171 | type: query 172 | datasource: 173 | type: __expr__ 174 | uid: __expr__ 175 | expression: B 176 | hide: false 177 | intervalMs: 1000 178 | maxDataPoints: 43200 179 | refId: C 180 | type: threshold 181 | dashboardUid: 280lKAr7k 182 | panelId: 6 183 | noDataState: OK 184 | execErrState: Error 185 | for: 10s 186 | annotations: 187 | __dashboardUid__: 280lKAr7k 188 | __panelId__: "6" 189 | summary: Latency is high 190 | isPaused: false 191 | contactPoints: 192 | - orgId: 1 193 | name: alerts-email-and-local-webhook 194 | receivers: 195 | - uid: 4e3bfe25-00cf-4173-b02b-16f077e539da 196 | type: email 197 | disableResolveMessage: false 198 | settings: 199 | addresses: alerts@example.org 200 | singleEmail: false 201 | - uid: ffc01bb5-d147-4890-a406-b2598f3cd0cc 202 | type: webhook 203 | disableResolveMessage: false 204 | settings: 205 | url: 'http://host.docker.internal:3333' 206 | policies: 207 | - orgId: 1 208 | receiver: alerts-email-and-local-webhook 209 | group_by: ['grafana_folder', 'alertname'] 210 | group_wait: 0s 211 | group_interval: 1s 212 | -------------------------------------------------------------------------------- /tealeaf-service/src/test/java/org/example/teahouse/tealeaf/TealeafServiceApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.example.teahouse.tealeaf; 2 | 3 | import org.example.teahouse.tealeaf.api.CreateTealeafRequest; 4 | import org.flywaydb.core.Flyway; 5 | import org.junit.jupiter.api.AfterEach; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.web.server.LocalServerPort; 13 | import org.springframework.test.context.ActiveProfiles; 14 | 15 | import static io.restassured.RestAssured.given; 16 | import static io.restassured.http.ContentType.JSON; 17 | import static org.hamcrest.Matchers.blankOrNullString; 18 | import static org.hamcrest.Matchers.equalTo; 19 | import static org.hamcrest.Matchers.not; 20 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 21 | 22 | @ActiveProfiles("test") 23 | @SpringBootTest(webEnvironment = RANDOM_PORT) 24 | class TealeafServiceApplicationTest { 25 | @LocalServerPort int port; 26 | 27 | @AfterEach 28 | void cleanDb(@Autowired Flyway flyway) { 29 | flyway.clean(); 30 | flyway.migrate(); 31 | } 32 | 33 | @Test 34 | void tealeavesEndpointShouldReturnTealeafResources() { 35 | given() 36 | .port(this.port) 37 | .accept(JSON) 38 | .when() 39 | .get("/tealeaves") 40 | .then() 41 | .statusCode(200) 42 | .body("page.totalElements", equalTo(3)) 43 | .body("_embedded.tealeaves.size()", equalTo(3)) 44 | .rootPath("_embedded.tealeaves.find { it.name == 'sencha' }") 45 | .body("id", equalTo("6b55663a-1b50-43f1-a3b3-40939e89c4ad")) 46 | .body("name", equalTo("sencha")) 47 | .body("type", equalTo("green")) 48 | .body("suggestedAmount", equalTo("3 g")) 49 | .body("suggestedWaterTemperature", equalTo("75 °C")) 50 | .body("suggestedSteepingTime", equalTo("3 min")) 51 | .detachRootPath("") 52 | .rootPath("_embedded.tealeaves.find { it.name == 'gyokuro' }") 53 | .body("id", equalTo("b00a63a4-9796-4c82-8dd0-5654e872dcf2")) 54 | .body("name", equalTo("gyokuro")) 55 | .body("type", equalTo("green")) 56 | .body("suggestedAmount", equalTo("2 g")) 57 | .body("suggestedWaterTemperature", equalTo("70 °C")) 58 | .body("suggestedSteepingTime", equalTo("2 min")) 59 | .detachRootPath("") 60 | .rootPath("_embedded.tealeaves.find { it.name == 'da hong pao' }") 61 | .body("id", equalTo("98928e21-922f-4bd0-b5e5-275a4328cf7f")) 62 | .body("name", equalTo("da hong pao")) 63 | .body("type", equalTo("black")) 64 | .body("suggestedAmount", equalTo("5 g")) 65 | .body("suggestedWaterTemperature", equalTo("99 °C")) 66 | .body("suggestedSteepingTime", equalTo("3 min")); 67 | } 68 | 69 | @ParameterizedTest 70 | @CsvSource({ 71 | "6b55663a-1b50-43f1-a3b3-40939e89c4ad,sencha,green,3 g,75 °C,3 min", 72 | "b00a63a4-9796-4c82-8dd0-5654e872dcf2,gyokuro,green,2 g,70 °C,2 min", 73 | "98928e21-922f-4bd0-b5e5-275a4328cf7f,da hong pao,black,5 g,99 °C,3 min" 74 | }) 75 | void tealeavesEndpointShouldReturnTealeafResourceById(String id, String name, String type, String amount, String temperature, String time) { 76 | given() 77 | .port(this.port) 78 | .accept(JSON) 79 | .when() 80 | .get("/tealeaves/" + id) 81 | .then() 82 | .statusCode(200) 83 | .body("id", equalTo(id)) 84 | .body("name", equalTo(name)) 85 | .body("type", equalTo(type)) 86 | .body("suggestedAmount", equalTo(amount)) 87 | .body("suggestedWaterTemperature", equalTo(temperature)) 88 | .body("suggestedSteepingTime", equalTo(time)); 89 | } 90 | 91 | @ParameterizedTest 92 | @CsvSource({ 93 | "6b55663a-1b50-43f1-a3b3-40939e89c4ad,sencha,green,3 g,75 °C,3 min", 94 | "b00a63a4-9796-4c82-8dd0-5654e872dcf2,gyokuro,green,2 g,70 °C,2 min", 95 | "98928e21-922f-4bd0-b5e5-275a4328cf7f,da hong pao,black,5 g,99 °C,3 min" 96 | }) 97 | void searchEndpointShouldFindTealeafResources(String id, String name, String type, String amount, String temperature, String time) { 98 | given() 99 | .port(this.port) 100 | .accept(JSON) 101 | .param("name", name) 102 | .when() 103 | .get("/tealeaves/search/findByName") 104 | .then() 105 | .statusCode(200) 106 | .body("id", equalTo(id)) 107 | .body("name", equalTo(name)) 108 | .body("type", equalTo(type)) 109 | .body("suggestedAmount", equalTo(amount)) 110 | .body("suggestedWaterTemperature", equalTo(temperature)) 111 | .body("suggestedSteepingTime", equalTo(time)); 112 | } 113 | 114 | @Test 115 | void tealeavesEndpointShouldSupportCreateAndDelete() { 116 | given() 117 | .port(this.port) 118 | .accept(JSON) 119 | .when() 120 | .get("/tealeaves") 121 | .then() 122 | .statusCode(200) 123 | .body("page.totalElements", equalTo(3)); 124 | 125 | given() 126 | .port(this.port) 127 | .accept(JSON) 128 | .when() 129 | .delete("/tealeaves") 130 | .then() 131 | .statusCode(204); 132 | 133 | given() 134 | .port(this.port) 135 | .accept(JSON) 136 | .when() 137 | .get("/tealeaves") 138 | .then() 139 | .statusCode(200) 140 | .body("page.totalElements", equalTo(0)); 141 | 142 | String id = given() 143 | .port(this.port) 144 | .accept(JSON) 145 | .contentType(JSON) 146 | .body(new CreateTealeafRequest("Ya Shi Xiang", "oolong", "3g", "3 min", "90 °C")) 147 | .when() 148 | .post("/tealeaves") 149 | .then() 150 | .statusCode(201) 151 | .body("id", not(blankOrNullString())) 152 | .body("name", equalTo("Ya Shi Xiang")) 153 | .body("type", equalTo("oolong")) 154 | .body("suggestedAmount", equalTo("3g")) 155 | .body("suggestedWaterTemperature", equalTo("90 °C")) 156 | .body("suggestedSteepingTime", equalTo("3 min")) 157 | .extract().body().path("id"); 158 | 159 | given() 160 | .port(this.port) 161 | .accept(JSON) 162 | .when() 163 | .get("/tealeaves") 164 | .then() 165 | .statusCode(200) 166 | .body("_embedded.tealeaves.size()", equalTo(1)) 167 | .rootPath("_embedded.tealeaves[0]") 168 | .body("id", equalTo(id)) 169 | .body("name", equalTo("Ya Shi Xiang")) 170 | .body("type", equalTo("oolong")) 171 | .body("suggestedAmount", equalTo("3g")) 172 | .body("suggestedWaterTemperature", equalTo("90 °C")) 173 | .body("suggestedSteepingTime", equalTo("3 min")); 174 | 175 | given() 176 | .port(this.port) 177 | .accept(JSON) 178 | .when() 179 | .get("/tealeaves/" + id) 180 | .then() 181 | .statusCode(200) 182 | .body("id", equalTo(id)) 183 | .body("name", equalTo("Ya Shi Xiang")) 184 | .body("type", equalTo("oolong")) 185 | .body("suggestedAmount", equalTo("3g")) 186 | .body("suggestedWaterTemperature", equalTo("90 °C")) 187 | .body("suggestedSteepingTime", equalTo("3 min")); 188 | 189 | given() 190 | .port(this.port) 191 | .accept(JSON) 192 | .when() 193 | .delete("/tealeaves/" + id) 194 | .then() 195 | .statusCode(204); 196 | 197 | given() 198 | .port(this.port) 199 | .accept(JSON) 200 | .when() 201 | .get("/tealeaves") 202 | .then() 203 | .statusCode(200) 204 | .body("page.totalElements", equalTo(0)); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | 118 | 119 | # Determine the Java command to use to start the JVM. 120 | if [ -n "$JAVA_HOME" ] ; then 121 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 122 | # IBM's JDK on AIX uses strange locations for the executables 123 | JAVACMD=$JAVA_HOME/jre/sh/java 124 | else 125 | JAVACMD=$JAVA_HOME/bin/java 126 | fi 127 | if [ ! -x "$JAVACMD" ] ; then 128 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 129 | 130 | Please set the JAVA_HOME variable in your environment to match the 131 | location of your Java installation." 132 | fi 133 | else 134 | JAVACMD=java 135 | if ! command -v java >/dev/null 2>&1 136 | then 137 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 138 | 139 | Please set the JAVA_HOME variable in your environment to match the 140 | location of your Java installation." 141 | fi 142 | fi 143 | 144 | # Increase the maximum file descriptors if we can. 145 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 146 | case $MAX_FD in #( 147 | max*) 148 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 149 | # shellcheck disable=SC2039,SC3045 150 | MAX_FD=$( ulimit -H -n ) || 151 | warn "Could not query maximum file descriptor limit" 152 | esac 153 | case $MAX_FD in #( 154 | '' | soft) :;; #( 155 | *) 156 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 157 | # shellcheck disable=SC2039,SC3045 158 | ulimit -n "$MAX_FD" || 159 | warn "Could not set maximum file descriptor limit to $MAX_FD" 160 | esac 161 | fi 162 | 163 | # Collect all arguments for the java command, stacking in reverse order: 164 | # * args from the command line 165 | # * the main class name 166 | # * -classpath 167 | # * -D...appname settings 168 | # * --module-path (only if needed) 169 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 170 | 171 | # For Cygwin or MSYS, switch paths to Windows format before running java 172 | if "$cygwin" || "$msys" ; then 173 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | --------------------------------------------------------------------------------