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

SWATCH-1934: Remove InstanceReportSort enum #2873

Merged
merged 1 commit into from Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 3 additions & 17 deletions api/rhsm-subscriptions-api-spec.yaml
Expand Up @@ -725,8 +725,9 @@ paths:
- name: sort
in: query
schema:
$ref: "#/components/schemas/InstanceReportSort"
description: "What property to sort by (optional)"
type: string
description: "What property to sort by. Options are: display_name, last_seen, billing_provider,
number_of_guests, category, or by a metric ID. (optional)"
- name: dir
in: query
schema:
Expand Down Expand Up @@ -1548,21 +1549,6 @@ components:
next: string
meta:
count: 10
InstanceReportSort:
type: string
enum:
- display_name
- last_seen
- Cores
- Sockets
- Core-seconds
- Instance-hours
- Storage-gibibyte-months
- Transfer-gibibytes
- vCPUs
- billing_provider
- number_of_guests
- category
InstanceData:
title: Root Type for Instance
description: The representation of a product cluster data
Expand Down
Expand Up @@ -31,12 +31,11 @@
import jakarta.ws.rs.core.UriInfo;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.candlepin.subscriptions.db.HostRepository;
Expand All @@ -55,7 +54,6 @@
import org.candlepin.subscriptions.utilization.api.model.InstanceData;
import org.candlepin.subscriptions.utilization.api.model.InstanceGuestReport;
import org.candlepin.subscriptions.utilization.api.model.InstanceMeta;
import org.candlepin.subscriptions.utilization.api.model.InstanceReportSort;
import org.candlepin.subscriptions.utilization.api.model.InstanceResponse;
import org.candlepin.subscriptions.utilization.api.model.MetaCount;
import org.candlepin.subscriptions.utilization.api.model.PageLinks;
Expand All @@ -75,23 +73,21 @@
@Slf4j
public class InstancesResource implements InstancesApi {

private final TallyInstanceViewRepository repository;
private final HostRepository hostRepository;
private final PageLinkCreator pageLinkCreator;

public static final Map<InstanceReportSort, String> INSTANCE_SORT_PARAM_MAPPING =
ImmutableMap.<InstanceReportSort, String>builder()
.put(InstanceReportSort.DISPLAY_NAME, "displayName")
.put(InstanceReportSort.LAST_SEEN, "lastSeen")
.put(InstanceReportSort.BILLING_PROVIDER, "hostBillingProvider")
.put(InstanceReportSort.NUMBER_OF_GUESTS, "numOfGuests")
.put(InstanceReportSort.CATEGORY, "key.measurementType")
.putAll(getUomSorts())
.put(InstanceReportSort.SOCKETS, "sockets")
public static final Map<String, String> FIELD_SORT_PARAM_MAPPING =
ImmutableMap.<String, String>builder()
.put("display_name", "displayName")
.put("last_seen", "lastSeen")
.put("billing_provider", "hostBillingProvider")
.put("number_of_guests", "numOfGuests")
.put("category", "key.measurementType")
.put("Sockets", "sockets")
.put("Cores", "cores")
.build();

public static final Map<InstanceReportSort, MetricId> SORT_TO_METRIC_ID_MAP =
ImmutableMap.copyOf(getSortToMetricIdMap());
public static final Set<String> METRICS_TO_SORT =
MetricId.getAll().stream().map(MetricId::getValue).collect(Collectors.toUnmodifiableSet());
public static final String METRICS_SORT_PARAM = "value";
private static final Sort.Order IMPLICIT_ORDER_TO_SORT = Sort.Order.by("id");

private static final Map<ReportCategory, List<HardwareMeasurementType>> CATEGORY_MAP =
Map.of(
Expand All @@ -100,6 +96,10 @@ public class InstancesResource implements InstancesApi {
ReportCategory.HYPERVISOR, List.of(HardwareMeasurementType.HYPERVISOR),
ReportCategory.CLOUD, new ArrayList<>(HardwareMeasurementType.getCloudProviderTypes()));

private final TallyInstanceViewRepository repository;
private final HostRepository hostRepository;
private final PageLinkCreator pageLinkCreator;

@Context UriInfo uriInfo;

public InstancesResource(
Expand Down Expand Up @@ -145,20 +145,13 @@ public InstanceResponse getInstancesByProduct(
ReportCategory reportCategory,
OffsetDateTime beginning,
OffsetDateTime ending,
InstanceReportSort sort,
String sort,
SortDirection dir) {

String orgId = ResourceUtils.getOrgId();

log.debug("Get instances api called for org_id: {} and product: {}", orgId, productId);

Sort.Direction dirValue = Sort.Direction.ASC;
if (dir == SortDirection.DESC) {
dirValue = Sort.Direction.DESC;
}
Sort.Order implicitOrder = Sort.Order.by("id");
Sort sortValue = Sort.by(implicitOrder);

Optional<MetricId> metricIdOptional = Optional.empty();
if (Objects.nonNull(uom)) {
try {
Expand Down Expand Up @@ -189,11 +182,8 @@ public InstanceResponse getInstancesByProduct(

List<InstanceData> payload;
Page<TallyInstanceView> instances;
if (sort != null) {
Sort.Order userDefinedOrder = new Sort.Order(dirValue, INSTANCE_SORT_PARAM_MAPPING.get(sort));
sortValue = Sort.by(userDefinedOrder, implicitOrder);
}
Pageable page = ResourceUtils.getPageable(offset, limit, sortValue);

Pageable page = ResourceUtils.getPageable(offset, limit, toSort(sort, dir));

OffsetDateTime now = OffsetDateTime.now();
OffsetDateTime start = Optional.ofNullable(beginning).orElse(now);
Expand All @@ -213,7 +203,10 @@ public InstanceResponse getInstancesByProduct(
// the selected month. This is also used for sorting purposes (same join). See
// org.candlepin.subscriptions.db.TallyInstanceViewSpecification#toPredicate and
// org.candlepin.subscriptions.db.TallyInstanceViewRepository#findAllBy.
MetricId referenceMetricId = metricIdOptional.orElse(SORT_TO_METRIC_ID_MAP.get(sort));
MetricId referenceMetricId = metricIdOptional.orElse(null);
if (referenceMetricId == null && sort != null && METRICS_TO_SORT.contains(sort)) {
referenceMetricId = MetricId.fromString(sort);
}

instances =
repository.findAllBy(
Expand Down Expand Up @@ -258,6 +251,24 @@ public InstanceResponse getInstancesByProduct(
.data(payload);
}

private static Sort toSort(String sort, SortDirection dir) {
Sort.Direction dirValue =
SortDirection.DESC.equals(dir) ? Sort.Direction.DESC : Sort.Direction.ASC;

Sort sortValue;

if (sort != null) {
String column =
METRICS_TO_SORT.contains(sort) ? METRICS_SORT_PARAM : FIELD_SORT_PARAM_MAPPING.get(sort);
Sort.Order userDefinedOrder = new Sort.Order(dirValue, column);
sortValue = Sort.by(userDefinedOrder, IMPLICIT_ORDER_TO_SORT);
} else {
sortValue = Sort.by(IMPLICIT_ORDER_TO_SORT);
}

return sortValue;
}

private static Boolean isPayg(Optional<Variant> variant) {
return variant
.map(Variant::getSubscription)
Expand Down Expand Up @@ -356,24 +367,4 @@ private static CloudProvider getCloudProviderByMeasurementType(
default -> null;
};
}

private static Map<InstanceReportSort, MetricId> getSortToMetricIdMap() {
return MetricId.getAll().stream()
.filter(
metricId ->
Arrays.stream(InstanceReportSort.values())
.map(InstanceReportSort::toString)
.filter(value -> !value.equals(MetricIdUtils.getSockets().getValue()))
.collect(Collectors.toSet())
.contains(metricId.getValue()))
.collect(
Collectors.toMap(
metricId -> InstanceReportSort.fromValue(metricId.getValue()),
Function.identity()));
}

private static Map<InstanceReportSort, String> getUomSorts() {
return getSortToMetricIdMap().keySet().stream()
.collect(Collectors.toMap(Function.identity(), key -> "value"));
}
}
Expand Up @@ -52,9 +52,7 @@
import org.candlepin.subscriptions.db.model.ServiceLevel;
import org.candlepin.subscriptions.db.model.TallyHostView;
import org.candlepin.subscriptions.db.model.Usage;
import org.candlepin.subscriptions.resource.InstancesResource;
import org.candlepin.subscriptions.test.TestClockConfiguration;
import org.candlepin.subscriptions.utilization.api.model.InstanceReportSort;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
Expand All @@ -78,8 +76,8 @@
@TestInstance(Lifecycle.PER_CLASS)
@Import(TestClockConfiguration.class)
class HostRepositoryTest {
private final String RHEL = "RHEL";
private final String COOL_PROD = "COOL_PROD";
private static final String RHEL = "RHEL";
private static final String COOL_PROD = "COOL_PROD";
private static final String DEFAULT_DISPLAY_NAME = "REDHAT_PWNS";
private static final String SANITIZED_MISSING_DISPLAY_NAME = "";
private static final String SORT_BY_MONTHLY_TOTALS = "monthlyTotals";
Expand Down Expand Up @@ -516,11 +514,7 @@ void testCanSortBySockets() {
SANITIZED_MISSING_DISPLAY_NAME,
0,
0,
PageRequest.of(
0,
10,
Sort.Direction.ASC,
InstancesResource.INSTANCE_SORT_PARAM_MAPPING.get(InstanceReportSort.SOCKETS)));
PageRequest.of(0, 10, Sort.Direction.ASC, "sockets"));
List<TallyHostView> found = hosts.stream().toList();

assertEquals(1, found.size());
Expand Down