|
| 1 | +package org.hypertrace.core.grpcutils.validation; |
| 2 | + |
| 3 | +import com.google.protobuf.Descriptors.FieldDescriptor; |
| 4 | +import com.google.protobuf.Message; |
| 5 | +import com.google.protobuf.util.JsonFormat; |
| 6 | +import io.grpc.Status; |
| 7 | +import org.hypertrace.core.grpcutils.context.RequestContext; |
| 8 | + |
| 9 | +public class GrpcValidatorUtils { |
| 10 | + private static final JsonFormat.Printer JSON_PRINTER = JsonFormat.printer(); |
| 11 | + |
| 12 | + private GrpcValidatorUtils() {} |
| 13 | + |
| 14 | + public static void validateRequestContextOrThrow(RequestContext requestContext) { |
| 15 | + if (requestContext.getTenantId().isEmpty()) { |
| 16 | + throw Status.INVALID_ARGUMENT |
| 17 | + .withDescription("Missing expected Tenant ID") |
| 18 | + .asRuntimeException(); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public static <T extends Message> void validateNonDefaultPresenceOrThrow( |
| 23 | + T source, int fieldNumber) { |
| 24 | + FieldDescriptor descriptor = source.getDescriptorForType().findFieldByNumber(fieldNumber); |
| 25 | + |
| 26 | + if (descriptor.isRepeated()) { |
| 27 | + validateNonDefaultPresenceRepeatedOrThrow(source, descriptor); |
| 28 | + } else if (!source.hasField(descriptor) |
| 29 | + || source.getField(descriptor).equals(descriptor.getDefaultValue())) { |
| 30 | + throw Status.INVALID_ARGUMENT |
| 31 | + .withDescription( |
| 32 | + String.format( |
| 33 | + "Expected field value %s but not present:%n %s", |
| 34 | + descriptor.getFullName(), printMessage(source))) |
| 35 | + .asRuntimeException(); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private static <T extends Message> void validateNonDefaultPresenceRepeatedOrThrow( |
| 40 | + T source, FieldDescriptor descriptor) { |
| 41 | + if (source.getRepeatedFieldCount(descriptor) == 0) { |
| 42 | + throw Status.INVALID_ARGUMENT |
| 43 | + .withDescription( |
| 44 | + String.format( |
| 45 | + "Expected at least 1 value for repeated field %s but not present:%n %s", |
| 46 | + descriptor.getFullName(), printMessage(source))) |
| 47 | + .asRuntimeException(); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public static String printMessage(Message message) { |
| 52 | + try { |
| 53 | + return JSON_PRINTER.print(message); |
| 54 | + } catch (Exception exception) { |
| 55 | + return message.toString(); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments