Refactor out creation of server TRIDs so they can be tested

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=152837185
This commit is contained in:
mcilwain 2017-04-11 11:28:11 -07:00 committed by Ben McIlwain
parent af942774f4
commit 8653d2f204
29 changed files with 174 additions and 62 deletions

View file

@ -50,6 +50,7 @@ public final class EppController {
@Inject EppMetric.Builder eppMetricBuilder;
@Inject EppMetrics eppMetrics;
@Inject BigQueryMetricsEnqueuer bigQueryMetricsEnqueuer;
@Inject ServerTridProvider serverTridProvider;
@Inject EppController() {}
/** Reads EPP XML, executes the matching flow, and returns an {@link EppOutput}. */
@ -83,7 +84,8 @@ public final class EppController {
Strings.repeat("=", 40));
// Return early by sending an error message, with no clTRID since we couldn't unmarshal it.
eppMetricBuilder.setStatus(e.getResult().getCode());
return getErrorResponse(e.getResult(), Trid.create(null));
return getErrorResponse(
e.getResult(), Trid.create(null, serverTridProvider.createServerTrid()));
}
if (!eppInput.getTargetIds().isEmpty()) {
eppMetricBuilder.setEppTarget(Joiner.on(',').join(eppInput.getTargetIds()));

View file

@ -152,6 +152,13 @@ public class FlowModule {
return credentials;
}
@Provides
@FlowScope
Trid provideTrid(EppInput eppInput, ServerTridProvider serverTridProvider) {
return Trid.create(
eppInput.getCommandWrapper().getClTrid(), serverTridProvider.createServerTrid());
}
@Provides
@FlowScope
@ClientId
@ -161,12 +168,6 @@ public class FlowModule {
return Strings.nullToEmpty(sessionMetadata.getClientId());
}
@Provides
@FlowScope
static Trid provideTrid(EppInput eppInput) {
return Trid.create(eppInput.getCommandWrapper().getClTrid());
}
@Provides
@FlowScope
static Class<? extends Flow> provideFlowClass(EppInput eppInput) {

View file

@ -0,0 +1,28 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import google.registry.model.eppcommon.Trid;
/**
* An interface that provides server Trids.
*
* @see Trid
*/
public interface ServerTridProvider {
/** Creates a new server Trid. */
public String createServerTrid();
}

View file

@ -0,0 +1,50 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static com.google.common.primitives.Longs.BYTES;
import com.google.common.io.BaseEncoding;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import javax.inject.Inject;
/** A server Trid provider that generates globally incrementing UUIDs. */
public class ServerTridProviderImpl implements ServerTridProvider {
private static final String SERVER_ID = getServerId();
private static final AtomicLong idCounter = new AtomicLong();
@Inject public ServerTridProviderImpl() {}
/** Creates a unique id for this server instance, as a base64 encoded UUID. */
private static String getServerId() {
UUID uuid = UUID.randomUUID();
ByteBuffer buffer =
ByteBuffer.allocate(BYTES * 2)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
return BaseEncoding.base64().encode(buffer.array());
}
@Override
public String createServerTrid() {
// The server id can be at most 64 characters. The SERVER_ID is at most 22 characters (128
// bits in base64), plus the dash. That leaves 41 characters, so we just append the counter in
// hex.
return String.format("%s-%x", SERVER_ID, idCounter.incrementAndGet());
}
}

View file

@ -0,0 +1,28 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import dagger.Module;
import dagger.Provides;
/** Dagger module for the server Trid provider. */
@Module
public class ServerTridProviderModule {
@Provides
static ServerTridProvider provideServerTridProvider(ServerTridProviderImpl defaultProvider) {
return defaultProvider;
}
}

View file

@ -14,13 +14,12 @@
package google.registry.model.eppcommon;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.BaseEncoding;
import com.googlecode.objectify.annotation.Embed;
import google.registry.model.ImmutableObject;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@ -34,19 +33,6 @@ import javax.xml.bind.annotation.XmlType;
@XmlType(propOrder = {"clientTransactionId", "serverTransactionId"})
public class Trid extends ImmutableObject {
private static final String SERVER_ID = getServerId();
private static final AtomicLong COUNTER = new AtomicLong();
/** Creates a unique id for this server instance, as a base64 encoded UUID. */
private static String getServerId() {
UUID uuid = UUID.randomUUID();
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.asLongBuffer()
.put(0, uuid.getMostSignificantBits())
.put(1, uuid.getLeastSignificantBits());
return BaseEncoding.base64().encode(buffer.array());
}
/** The server transaction id. */
@XmlElement(name = "svTRID", namespace = "urn:ietf:params:xml:ns:epp-1.0")
String serverTransactionId;
@ -63,17 +49,9 @@ public class Trid extends ImmutableObject {
return clientTransactionId;
}
public static Trid create(String clientTransactionId) {
Trid instance = new Trid();
instance.clientTransactionId = clientTransactionId;
// The server id can be at most 64 characters. The SERVER_ID is at most 22 characters (128 bits
// in base64), plus the dash. That leaves 41 characters, so we just append the counter in hex.
instance.serverTransactionId = String.format("%s-%x", SERVER_ID, COUNTER.incrementAndGet());
return instance;
}
@VisibleForTesting
public static Trid create(String clientTransactionId, String serverTransactionId) {
public static Trid create(@Nullable String clientTransactionId, String serverTransactionId) {
checkArgumentNotNull(serverTransactionId, "serverTransactionId cannot be null");
Trid instance = new Trid();
instance.clientTransactionId = clientTransactionId;
instance.serverTransactionId = serverTransactionId;

View file

@ -17,6 +17,7 @@ package google.registry.module.frontend;
import dagger.Component;
import google.registry.braintree.BraintreeModule;
import google.registry.config.RegistryConfig.ConfigModule;
import google.registry.flows.ServerTridProviderModule;
import google.registry.flows.custom.CustomLogicFactoryModule;
import google.registry.keyring.api.DummyKeyringModule;
import google.registry.keyring.api.KeyModule;
@ -51,6 +52,7 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
ModulesServiceModule.class,
ServerTridProviderModule.class,
StackdriverModule.class,
SystemClockModule.class,
SystemSleeperModule.class,

View file

@ -17,6 +17,7 @@ package google.registry.module.tools;
import dagger.Component;
import google.registry.config.RegistryConfig.ConfigModule;
import google.registry.export.DriveModule;
import google.registry.flows.ServerTridProviderModule;
import google.registry.flows.custom.CustomLogicFactoryModule;
import google.registry.gcs.GcsServiceModule;
import google.registry.groups.DirectoryModule;
@ -57,12 +58,13 @@ import javax.inject.Singleton;
Jackson2Module.class,
KeyModule.class,
ModulesServiceModule.class,
ServerTridProviderModule.class,
SystemClockModule.class,
SystemSleeperModule.class,
ToolsRequestComponentModule.class,
UrlFetchTransportModule.class,
UseAppIdentityCredentialForGoogleApisModule.class,
UserServiceModule.class,
SystemClockModule.class,
SystemSleeperModule.class,
})
interface ToolsComponent {
ToolsRequestHandler requestHandler();

View file

@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.appengine.tools.cloudstorage.GcsFilename;
@ -25,6 +26,8 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.io.BaseEncoding;
import com.googlecode.objectify.Key;
import google.registry.config.RegistryConfig.Config;
import google.registry.flows.ServerTridProvider;
import google.registry.flows.ServerTridProviderImpl;
import google.registry.gcs.GcsUtils;
import google.registry.model.EppResource;
import google.registry.model.EppResource.ForeignKeyedEppResource;
@ -70,6 +73,8 @@ public class RdeImportUtils {
private final String escrowBucketName;
private final GcsUtils gcsUtils;
private static final ServerTridProvider serverTridProvider = new ServerTridProviderImpl();
@Inject
public RdeImportUtils(
Ofy ofy, Clock clock, @Config("rdeImportBucket") String escrowBucketName, GcsUtils gcsUtils) {
@ -175,7 +180,8 @@ public class RdeImportUtils {
// Client trids must be a token between 3 and 64 characters long
// Base64 encoded UUID string meets this requirement
return Trid.create(
"Import_" + BaseEncoding.base64().encode(UUID.randomUUID().toString().getBytes()));
"Import_" + BaseEncoding.base64().encode(UUID.randomUUID().toString().getBytes(US_ASCII)),
serverTridProvider.createServerTrid());
}
public static BillingEvent.Recurring createAutoRenewBillingEventForDomainImport(

View file

@ -22,6 +22,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import google.registry.flows.EppTestComponent.FakeServerTridProvider;
import google.registry.model.eppcommon.Trid;
import google.registry.model.eppoutput.EppOutput;
import google.registry.model.eppoutput.EppResponse;
@ -86,12 +87,14 @@ public class EppControllerTest extends ShardableTestCase {
eppController.bigQueryMetricsEnqueuer = metricsEnqueuer;
eppController.flowComponentBuilder = flowComponentBuilder;
eppController.eppMetrics = eppMetrics;
eppController.serverTridProvider = new FakeServerTridProvider();
}
@Test
public void testMarshallingUnknownError() throws Exception {
marshal(
EppController.getErrorResponse(Result.create(Code.COMMAND_FAILED), Trid.create(null)),
EppController.getErrorResponse(
Result.create(Code.COMMAND_FAILED), Trid.create(null, "server-trid")),
ValidationMode.STRICT);
}

View file

@ -115,6 +115,19 @@ interface EppTestComponent {
Sleeper provideSleeper() {
return sleeper;
}
@Provides
ServerTridProvider provideServerTridProvider() {
return new FakeServerTridProvider();
}
}
public static class FakeServerTridProvider implements ServerTridProvider {
@Override
public String createServerTrid() {
return "server-trid";
}
}
/** Subcomponent for request scoped injections. */

View file

@ -89,7 +89,7 @@ public class DomainAllocateFlowTest
private static final String SMD_ID = "1-1";
private static final String CLIENT_ID = "TheRegistrar";
private static final Trid TRID = Trid.create("ABC-123");
private static final Trid TRID = Trid.create("ABC-123", "server-trid");
/** The applicationId, expressed as a base 10 String. */
private String applicationId = "2-TLD";

View file

@ -110,7 +110,7 @@ public class ContactResourceTest extends EntityTestCase {
Key.create(BillingEvent.OneTime.class, 1)))
.setTransferRequestTime(clock.nowUtc())
.setTransferStatus(TransferStatus.SERVER_APPROVED)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.build()));
}

View file

@ -90,7 +90,7 @@ public class DomainApplicationTest extends EntityTestCase {
.setDsData(ImmutableSet.of(DelegationSignerData.create(1, 2, 3, new byte[] {0, 1, 2})))
.setLaunchNotice(
LaunchNotice.create("tcnid", "validatorId", START_OF_TIME, START_OF_TIME))
.setCreationTrid(Trid.create("client creation trid"))
.setCreationTrid(Trid.create("client-creation-trid", "server-trid"))
.setPhase(LaunchPhase.LANDRUSH)
// TODO(b/32447342): set period
.setEncodedSignedMarks(ImmutableList.of(EncodedSignedMark.create("base64", "abcdefg=")))

View file

@ -137,7 +137,7 @@ public class DomainResourceTest extends EntityTestCase {
.setServerApproveAutorenewPollMessage(autorenewPollKey)
.setTransferRequestTime(clock.nowUtc().plusDays(1))
.setTransferStatus(TransferStatus.SERVER_APPROVED)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.setDeletePollMessage(onetimePollKey)
.setAutorenewBillingEvent(recurringBillKey)

View file

@ -69,7 +69,7 @@ public class HostResourceTest extends EntityTestCase {
Key.create(BillingEvent.OneTime.class, 1)))
.setTransferRequestTime(clock.nowUtc())
.setTransferStatus(TransferStatus.SERVER_APPROVED)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.build());
host =

View file

@ -70,7 +70,7 @@ public class PollMessageExternalKeyConverterTest {
.setXmlBytes("<xml></xml>".getBytes(UTF_8))
.setModificationTime(clock.nowUtc())
.setClientId("foo")
.setTrid(Trid.create("ABC-123"))
.setTrid(Trid.create("ABC-123", "server-trid"))
.setBySuperuser(false)
.setReason("reason")
.setRequestedByRegistrar(false)

View file

@ -43,7 +43,7 @@ public class PollMessageTest extends EntityTestCase {
.setXmlBytes("<xml></xml>".getBytes(UTF_8))
.setModificationTime(clock.nowUtc())
.setClientId("foo")
.setTrid(Trid.create("ABC-123"))
.setTrid(Trid.create("ABC-123", "server-trid"))
.setBySuperuser(false)
.setReason("reason")
.setRequestedByRegistrar(false)

View file

@ -44,7 +44,7 @@ public class HistoryEntryTest extends EntityTestCase {
.setModificationTime(clock.nowUtc())
.setClientId("foo")
.setOtherClientId("otherClient")
.setTrid(Trid.create("ABC-123"))
.setTrid(Trid.create("ABC-123", "server-trid"))
.setBySuperuser(false)
.setReason("reason")
.setRequestedByRegistrar(false)

View file

@ -337,7 +337,7 @@ public class ContactResourceToXjcConverterTest {
.setTransferRequestTime(DateTime.parse("1925-04-19TZ"))
.setPendingTransferExpirationTime(DateTime.parse("1925-04-21TZ"))
.setTransferStatus(TransferStatus.SERVER_APPROVED)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.setDisclose(new Disclose.Builder()
.setFlag(true)

View file

@ -352,7 +352,7 @@ public class DomainResourceToXjcConverterTest {
Key.create(billingEvent)))
.setTransferRequestTime(DateTime.parse("1919-01-01T00:00:00Z"))
.setTransferStatus(TransferStatus.PENDING)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.build();
clock.advanceOneMilli();

View file

@ -177,7 +177,7 @@ final class RdeFixtures {
Key.create(billingEvent)))
.setTransferRequestTime(DateTime.parse("1919-01-01T00:00:00Z"))
.setTransferStatus(TransferStatus.PENDING)
.setTransferRequestTrid(Trid.create("client trid"))
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.build();
clock.advanceOneMilli();

View file

@ -127,7 +127,7 @@ public class RdeContactImportActionTest extends MapreduceTestCase<RdeContactImpo
return new HistoryEntry.Builder()
.setType(HistoryEntry.Type.RDE_IMPORT)
.setClientId(clid)
.setTrid(Trid.create(null))
.setTrid(Trid.create("client-trid", "server-trid"))
.setModificationTime(DateTime.now())
.setXmlBytes(objectXml)
.setBySuperuser(true)

View file

@ -340,7 +340,7 @@ public class RdeDomainImportActionTest extends MapreduceTestCase<RdeDomainImport
return new HistoryEntry.Builder()
.setType(HistoryEntry.Type.RDE_IMPORT)
.setClientId(clid)
.setTrid(Trid.create(null))
.setTrid(Trid.create("client-trid", "server-trid"))
.setModificationTime(DateTime.now())
.setXmlBytes(objectXml)
.setBySuperuser(true)

View file

@ -158,7 +158,7 @@ public class RdeHostImportActionTest extends MapreduceTestCase<RdeHostImportActi
return new HistoryEntry.Builder()
.setType(HistoryEntry.Type.RDE_IMPORT)
.setClientId(clid)
.setTrid(Trid.create(null))
.setTrid(Trid.create("client-trid", "server-trid"))
.setModificationTime(DateTime.now())
.setXmlBytes(objectXml)
.setBySuperuser(true)

View file

@ -47,7 +47,7 @@ public class EppExceptionSubject extends Subject<EppExceptionSubject, EppExcepti
try {
marshal(
EppOutput.create(new EppResponse.Builder()
.setTrid(Trid.create(null))
.setTrid(Trid.create(null, "server-trid"))
.setResult(actual().getResult())
.build()),
ValidationMode.STRICT);

View file

@ -283,7 +283,7 @@ public final class FullFieldsTestEntityHelper {
.setXmlBytes(xml.getBytes(UTF_8))
.setModificationTime(modificationTime)
.setClientId("foo")
.setTrid(Trid.create("ABC-123"))
.setTrid(Trid.create("ABC-123", "server-trid"))
.setBySuperuser(false)
.setReason(reason)
.setRequestedByRegistrar(false);

View file

@ -102,7 +102,7 @@ public class AllocateDomainCommandTest extends CommandTestCase<AllocateDomainCom
.setParent(application)
.setClientId("NewRegistrar")
.setModificationTime(application.getCreationTime())
.setTrid(Trid.create("ABC-123"))
.setTrid(Trid.create("ABC-123", "server-trid"))
.setXmlBytes(toByteArray(getResource(AllocateDomainCommandTest.class, xmlFile)))
.build());
}

View file

@ -45,7 +45,6 @@ import org.junit.Test;
public class UpdateApplicationStatusCommandTest
extends CommandTestCase<UpdateApplicationStatusCommand> {
private Trid trid = Trid.create("ABC123");
private DomainApplication domainApplication;
private DateTime creationTime;
@ -71,7 +70,7 @@ public class UpdateApplicationStatusCommandTest
new HistoryEntry.Builder()
.setParent(domainApplication)
.setModificationTime(creationTime)
.setTrid(trid)
.setTrid(Trid.create("ABC123", "server-trid"))
.setType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE)
.build());
@ -81,7 +80,7 @@ public class UpdateApplicationStatusCommandTest
new HistoryEntry.Builder()
.setParent(domainApplication)
.setModificationTime(creationTime)
.setTrid(Trid.create("ABC124"))
.setTrid(Trid.create("ABC124", "server-trid"))
.setType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE)
.build());
}
@ -106,7 +105,7 @@ public class UpdateApplicationStatusCommandTest
.doesNotHaveApplicationStatus(REJECTED);
assertThat(getPollMessageCount()).isEqualTo(0);
Trid creationTrid = Trid.create("DEF456");
Trid creationTrid = Trid.create("DEF456", "server-trid");
persistResource(reloadResource(domainApplication).asBuilder()
.setCreationTrid(creationTrid)
.build());
@ -144,7 +143,7 @@ public class UpdateApplicationStatusCommandTest
.doesNotHaveApplicationStatus(ALLOCATED);
assertThat(getPollMessageCount()).isEqualTo(0);
Trid creationTrid = Trid.create("DEF456");
Trid creationTrid = Trid.create("DEF456", "server-trid");
persistResource(reloadResource(domainApplication).asBuilder()
.setCreationTrid(creationTrid)
.build());
@ -178,7 +177,7 @@ public class UpdateApplicationStatusCommandTest
.hasStatusValue(StatusValue.PENDING_CREATE);
assertThat(getPollMessageCount()).isEqualTo(0);
Trid creationTrid = Trid.create("DEF456");
Trid creationTrid = Trid.create("DEF456", "server-trid");
persistResource(reloadResource(domainApplication).asBuilder()
.setCreationTrid(creationTrid)
.build());
@ -229,7 +228,7 @@ public class UpdateApplicationStatusCommandTest
PollMessage pollMessage = getFirstPollMessage();
DomainPendingActionNotificationResponse response = (DomainPendingActionNotificationResponse)
FluentIterable.from(pollMessage.getResponseData()).first().get();
assertThat(response.getTrid()).isEqualTo(trid);
assertThat(response.getTrid()).isEqualTo(Trid.create("ABC123", "server-trid"));
}
@Test