Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/scaled testing #878

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@

package cwms.cda.data.dto.location.kind;

import static java.util.Comparator.comparing;

import com.fasterxml.jackson.annotation.JsonProperty;
import cwms.cda.data.dto.CwmsDTOBase;
import cwms.cda.data.dto.CwmsDTOValidator;
Expand All @@ -41,6 +39,7 @@
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Comparator.comparing;

public abstract class PhysicalStructureChange<T extends Setting> extends CwmsDTOBase {
@JsonProperty(required = true)
Expand Down Expand Up @@ -235,6 +234,7 @@ public B withChangeDate(Instant changeDate) {
}

public B withSettings(List<T> settings) {
this.settings.clear();
settings.forEach(s -> {
if (!this.settings.add(s)) {
throw new FormattingException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public void sessionEvent(SessionEvent event) {
.wrappedRegister(user.getJSessionId(), mcup, "CLIENT-CERT", null,null);
}
} catch(RuntimeException ex) {
throw new Exception("User registration failed",ex);
// throw new Exception("User registration failed",ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
/*
* MIT License
* Copyright (c) 2024 Hydrologic Engineering Center
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package cwms.cda.api.location.kind;

import com.google.common.flogger.FluentLogger;
import cwms.cda.api.Controllers;
import cwms.cda.api.enums.UnitSystem;
import cwms.cda.api.errors.NotFoundException;
import cwms.cda.data.dao.LocationsDaoImpl;
import cwms.cda.data.dao.location.kind.BaseOutletDaoIT;
import cwms.cda.data.dao.location.kind.OutletDao;
import cwms.cda.data.dao.location.kind.ProjectStructureIT;
import cwms.cda.data.dto.CwmsId;
import cwms.cda.data.dto.Location;
import cwms.cda.data.dto.LookupType;
import cwms.cda.data.dto.location.kind.GateChange;
import cwms.cda.data.dto.location.kind.GateSetting;
import cwms.cda.data.dto.location.kind.Outlet;
import cwms.cda.formatters.Formats;
import fixtures.CwmsDataApiSetupCallback;
import io.restassured.filter.log.LogDetail;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.Instant;
import java.time.Period;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.servlet.http.HttpServletResponse;
import mil.army.usace.hec.metadata.constants.NumericalConstants;
import mil.army.usace.hec.test.database.CwmsDatabaseContainer;
import org.jooq.DSLContext;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import usace.cwms.db.jooq.codegen.packages.CWMS_PROJECT_PACKAGE;
import static cwms.cda.api.Controllers.*;
import static cwms.cda.data.dao.DaoTest.getDslContext;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.*;

class GateChangeScaleTest extends BaseOutletDaoIT {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disable the test, so it's not run in automation

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't disable the test. use @EnableIfProperty (that might not be exact) so we don't need to change code to run the test when needed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's a good idea, thank you. Didn't know that was a thing.


private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass();
private static final CwmsId PROJECT_ID = new CwmsId.Builder().withOfficeId(OFFICE_ID).withName("PROJECT3").build();
private static final Location PROJECT_LOCATION = buildProjectLocation(PROJECT_ID.getName());
private static final String CONDUIT_GATE_RATING_SPEC_ID = PROJECT_ID.getName() + ".Opening-ConduitGate,Elev;Flow-ConduitGate.Standard.Production";
private static final CwmsId CONDUIT_GATE_RATING_GROUP = new CwmsId.Builder()
.withName("Rating-" + PROJECT_ID.getName() + "-ConduitGate")
.withOfficeId(OFFICE_ID)
.build();

private static final TemporalAmount INTERVAL = Duration.of(5, ChronoUnit.MINUTES);
private static final ZonedDateTime START = ZonedDateTime.of(2020, 1, 1, 0, 0, 0, 0, NumericalConstants.UTC_ZONEID);
private static final ZonedDateTime END = START.plusYears(1).plus(INTERVAL);

@BeforeAll
public static void setup() throws Exception {
//1 year of 5 minute gate change data for 18 gates
CwmsDatabaseContainer<?> databaseLink = CwmsDataApiSetupCallback.getDatabaseLink();
databaseLink.connection(c -> {
DSLContext context = getDslContext(c, OFFICE_ID);
CWMS_PROJECT_PACKAGE.call_STORE_PROJECT(context.configuration(), buildProject(PROJECT_LOCATION), "T");

OutletDao dao = new OutletDao(context);
try {
dao.retrieveOperationalChanges(PROJECT_ID, END.minus(INTERVAL).toInstant(), END.toInstant(), true, true,
UnitSystem.EN, 2);
LOGGER.atSevere().log("Found existing operation changes. Not attempting to generate and store changes again.");
return;
} catch (NotFoundException ex) {
LOGGER.atSevere().log("Could not find any changes at the end of the period. Generating and storing changes.");
}

String locPrefix = PROJECT_ID.getName() + "-CG";
CwmsId.Builder idBuilder = new CwmsId.Builder().withOfficeId(OFFICE_ID);
List<CwmsId> outletIds = IntStream.rangeClosed(1, 18)
.mapToObj(i -> locPrefix + String.format("%03d", i))
.map(name -> idBuilder.withName(name).build())
.collect(Collectors.toList());
List<Location> allLocs = outletIds.stream()
.map(CwmsId::getName)
.map(ProjectStructureIT::buildProjectLocation)
.collect(Collectors.toList());
Outlet.Builder outBuilder = new Outlet.Builder().withRatingGroupId(CONDUIT_GATE_RATING_GROUP)
.withProjectId(PROJECT_ID);
List<Outlet> outlets = allLocs.stream()
.map(loc -> outBuilder.withLocation(loc).build())
.collect(Collectors.toList());

List<List<Instant>> dateBatches = buildBatchDates();
LookupType compType = new LookupType.Builder().withActive(true)
.withDisplayValue("A")
.withOfficeId("CWMS")
.withTooltip("Adjusted by an automated method")
.build();
LookupType releaseReason = new LookupType.Builder().withActive(true)
.withDisplayValue("O")
.withOfficeId("CWMS")
.withTooltip("Other release")
.build();
GateSetting.Builder settingBuilder = new GateSetting.Builder().withOpening(15.)
.withOpeningParameter("Elev")
.withInvertElevation(5.)
.withOpeningUnits("ft");
GateChange.Builder changeBuilder = new GateChange.Builder().withProjectId(PROJECT_ID)
.withDischargeComputationType(compType)
.withReasonType(releaseReason)
.withProtected(false)
.withNewTotalDischargeOverride(1.5)
.withOldTotalDischargeOverride(2.0)
.withDischargeUnits("cfs")
.withPoolElevation(50.)
.withTailwaterElevation(30.)
.withElevationUnits("ft")
.withNotes("Notes");
List<List<GateChange>> changes = dateBatches.stream()
.map(dates -> buildGateChanges(dates, changeBuilder, settingBuilder,
outletIds))
.collect(Collectors.toList());

LOGGER.atSevere().log("Storing locations...");
allLocs.forEach(loc -> storeLocLogException(context, loc));
LOGGER.atSevere().log("Storing outlets...");
outlets.forEach(outlet -> storeOutlet(context, outlet));
LOGGER.atSevere().log("Storing rating spec id...");
createRatingSpecForOutlet(context, outlets.get(0), CONDUIT_GATE_RATING_SPEC_ID);

LOGGER.atSevere().log("Storing changes...");
changes.forEach(changeBatch -> {
LOGGER.atSevere().log("Storing " + changeBatch.size() + " changes from " + changeBatch.get(0).getChangeDate() + " to " + changeBatch.get(changeBatch.size() - 1));
dao.storeOperationalChanges(changeBatch, true);
});

}, CwmsDataApiSetupCallback.getWebUser());
}

@Test
void scaling_test() {
//Generate 18 outlets, 5 minute data, for 1 year
//location: keystone dam
//figure out how big the payload is.
int pageSize = (int) (TimeUnit.DAYS.toMinutes(14) / 15);

LOGGER.atInfo().log("Retrieving changes with page size: " + pageSize);

String body = given().log()
.ifValidationFails(LogDetail.ALL, true)
.contentType(Formats.JSONV1)
.when()
.redirects()
.follow(true)
.redirects()
.max(3)
.queryParam(BEGIN, START.toInstant().toString())
.queryParam(Controllers.END, END.toInstant().toString())
.queryParam(START_TIME_INCLUSIVE, true)
.queryParam(END_TIME_INCLUSIVE, true)
.queryParam(PAGE_SIZE, pageSize)
.get("projects/" + OFFICE_ID + "/" + PROJECT_ID.getName() + "/gate-changes")
.then()
.log()
.ifValidationFails(LogDetail.ALL, true)
.assertThat()
.statusCode(is(HttpServletResponse.SC_OK))
.extract()
.body()
.asString();

assertNotNull(body);
assertFalse(body.isEmpty());

LOGGER.atSevere().log("Output character length: " + body.length() + "\n" +
Charset.defaultCharset().displayName() + " byte length: " + body.getBytes().length);
}

private static List<List<Instant>> buildBatchDates() {
TemporalAmount batch = Period.ofWeeks(2);
ZonedDateTime batchStart = START;
ZonedDateTime batchEnd = START.plus(batch);
List<List<Instant>> dateBatches = new ArrayList<>();

while (batchStart.isBefore(END)) {
List<Instant> times = new ArrayList<>();
dateBatches.add(times);
ZonedDateTime nextInterval = batchStart;

while (nextInterval.isBefore(batchEnd)) {
times.add(nextInterval.toInstant());
nextInterval = nextInterval.plus(INTERVAL);
}

batchStart = batchStart.plus(batch);
batchEnd = batchEnd.plus(batch);
}
return dateBatches;
}

private static List<GateChange> buildGateChanges(List<Instant> dates, GateChange.Builder changeBuilder, GateSetting.Builder settingBuilder, List<CwmsId> outletIds) {
return dates.stream().map(date -> {
List<GateSetting> settings = outletIds.stream()
.map(id -> settingBuilder.withLocationId(id).build())
.collect(Collectors.toList());
return changeBuilder.withChangeDate(date).withSettings(settings).build();
}).collect(Collectors.toList());
}

private static void storeLocLogException(DSLContext context, Location loc) throws RuntimeException {
LocationsDaoImpl dao = new LocationsDaoImpl(context);
String locName = loc.getOfficeId() + "." + loc.getName();
try {
dao.getLocation(loc.getName(), UnitSystem.EN.getValue(), OFFICE_ID);
LOGGER.atInfo().log("Location already exists: " + locName);
} catch (NotFoundException ex) {
LOGGER.atInfo().log("No location found for " + locName + " storing it.");
try {
dao.storeLocation(loc);
} catch (IOException ex2) {
String msg = "Unable to store location data for " + locName;
LOGGER.atSevere().log(msg);
throw new RuntimeException(msg, ex2);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import com.google.common.flogger.FluentLogger;
import cwms.cda.api.errors.NotFoundException;
import cwms.cda.data.dao.DeleteRule;
import cwms.cda.data.dao.LocationGroupDao;
import cwms.cda.data.dto.AssignedLocation;
import cwms.cda.data.dto.LocationGroup;
Expand Down Expand Up @@ -63,4 +64,15 @@ public static void createRatingSpecForOutlet(DSLContext context, Outlet outlet,
locGroupDao.create(realGroup);
}
}

public static void storeOutlet(DSLContext context, Outlet outlet) {
OutletDao dao = new OutletDao(context);
dao.storeOutlet(outlet, false);
}

public static void deleteOutlet(DSLContext context, Outlet outlet) {
OutletDao outletDao = new OutletDao(context);
outletDao.deleteOutlet(outlet.getLocation().getOfficeId(), outlet.getLocation().getName(),
DeleteRule.DELETE_ALL);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,15 @@ static void setup() throws Exception {
CwmsDatabaseContainer<?> databaseLink = CwmsDataApiSetupCallback.getDatabaseLink();
databaseLink.connection(c -> {
DSLContext context = getDslContext(c, OFFICE_ID);
OutletDao outletDao = new OutletDao(context);
deleteLocation(context, TG_LOC4_ID.getOfficeId(), TG_LOC4_ID.getName());
try {
storeLocation(context, TAINTER_GATE_1_LOC);
storeLocation(context, TAINTER_GATE_2_LOC);
storeLocation(context, TAINTER_GATE_3_LOC);
storeLocation(context, BOX_CULVERT_1_LOC);
outletDao.storeOutlet(TAINTER_GATE_1_OUTLET, false);
outletDao.storeOutlet(TAINTER_GATE_2_OUTLET, false);
outletDao.storeOutlet(BOX_CULVERT_1_OUTLET, false);
storeOutlet(context, TAINTER_GATE_1_OUTLET);
storeOutlet(context, TAINTER_GATE_2_OUTLET);
storeOutlet(context, BOX_CULVERT_1_OUTLET);
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand All @@ -91,15 +90,12 @@ static void tearDown() throws Exception {
CwmsDatabaseContainer<?> databaseLink = CwmsDataApiSetupCallback.getDatabaseLink();
databaseLink.connection(c -> {
DSLContext context = getDslContext(c, OFFICE_ID);
OutletDao outletDao = new OutletDao(context);
deleteLocationGroup(context, TAINTER_GATE_1_OUTLET);
deleteLocationGroup(context, TAINTER_GATE_2_OUTLET);
deleteLocationGroup(context, BOX_CULVERT_1_OUTLET);
outletDao.deleteOutlet(TAINTER_GATE_1_LOC.getOfficeId(), TAINTER_GATE_1_LOC.getName(),
DeleteRule.DELETE_ALL);
outletDao.deleteOutlet(TAINTER_GATE_2_LOC.getOfficeId(), TAINTER_GATE_2_LOC.getName(),
DeleteRule.DELETE_ALL);
outletDao.deleteOutlet(BOX_CULVERT_1_LOC.getOfficeId(), BOX_CULVERT_1_LOC.getName(), DeleteRule.DELETE_ALL);
deleteOutlet(context, TAINTER_GATE_1_OUTLET);
deleteOutlet(context, TAINTER_GATE_2_OUTLET);
deleteOutlet(context, BOX_CULVERT_1_OUTLET);
deleteLocation(context, TAINTER_GATE_1_LOC.getOfficeId(), TAINTER_GATE_1_LOC.getName());
deleteLocation(context, TAINTER_GATE_2_LOC.getOfficeId(), TAINTER_GATE_2_LOC.getName());
deleteLocation(context, TAINTER_GATE_3_LOC.getOfficeId(), TAINTER_GATE_3_LOC.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ public static void storeLocation(DSLContext context, Location loc) throws IOExce
locationsDao.storeLocation(loc);
}

public static void deleteLocation(DSLContext context, Location loc) {
deleteLocation(context, loc.getOfficeId(), loc.getName());
}
public static void deleteLocation(DSLContext context, String officeId, String locId) {
LocationsDaoImpl locationsDao = new LocationsDaoImpl(context);
try {
Expand Down
Loading