DeReference the codebase

This change replaces all Ref objects in the code with Key objects. These are
stored in datastore as the same object (raw datastore keys), so this is not
a model change.

Our best practices doc says to use Keys not Refs because:
 * The .get() method obscures what's actually going on
   - Much harder to visually audit the code for datastore loads
   - Hard to distinguish Ref<T> get()'s from Optional get()'s and Supplier get()'s
 * Implicit ofy().load() offers much less control
   - Antipattern for ultimate goal of making Ofy injectable
   - Can't control cache use or batch loading without making ofy() explicit anyway
 * Serialization behavior is surprising and could be quite dangerous/incorrect
   - Can lead to serialization errors. If it actually worked "as intended",
     it would lead to a Ref<> on a serialized object being replaced upon
     deserialization with a stale copy of the old value, which could potentially
     break all kinds of transactional expectations
 * Having both Ref<T> and Key<T> introduces extra boilerplate everywhere
   - E.g. helper methods all need to have Ref and Key overloads, or you need to
     call .key() to get the Key<T> for every Ref<T> you want to pass in
   - Creating a Ref<T> is more cumbersome, since it doesn't have all the create()
     overloads that Key<T> has, only create(Key<T>) and create(Entity) - no way to
     create directly from kind+ID/name, raw Key, websafe key string, etc.

(Note that Refs are treated specially by Objectify's @Load method and Keys are not;
we don't use that feature, but it is the one advantage Refs have over Keys.)

The direct impetus for this change is that I am trying to audit our use of memcache,
and the implicit .get() calls to datastore were making that very hard.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=131965491
This commit is contained in:
cgoldfeder 2016-09-01 10:44:23 -07:00 committed by Ben McIlwain
parent 1a60073b24
commit 5098b03af4
119 changed files with 772 additions and 817 deletions

View file

@ -17,7 +17,7 @@ package google.registry.flows;
import static google.registry.model.eppoutput.Result.Code.SuccessWithActionPending;
import static google.registry.model.ofy.ObjectifyService.ofy;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Work;
import google.registry.flows.EppException.AssociationProhibitsOperationException;
import google.registry.model.EppResource;
@ -50,7 +50,7 @@ public abstract class ResourceAsyncDeleteFlow
// that would be hard to reason about, and there's no real gain in doing so.
return false;
}
return isLinkedForFailfast(fki.getReference());
return isLinkedForFailfast(fki.getResourceKey());
}
});
if (isLinked) {
@ -58,8 +58,8 @@ public abstract class ResourceAsyncDeleteFlow
}
}
/** Subclasses must override this to check if the supplied reference has incoming links. */
protected abstract boolean isLinkedForFailfast(Ref<R> ref);
/** Subclasses must override this to check if the supplied key has incoming links. */
protected abstract boolean isLinkedForFailfast(Key<R> key);
@Override
protected final R createOrMutateResource() {

View file

@ -16,7 +16,7 @@ package google.registry.flows.async;
import static google.registry.flows.ResourceFlowUtils.handlePendingTransferOnDelete;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DomainBase;
import google.registry.model.reporting.HistoryEntry;
@ -46,8 +46,8 @@ public class DeleteContactResourceAction extends DeleteEppResourceAction<Contact
@Override
protected boolean isLinked(
DomainBase domain, Ref<ContactResource> targetResourceRef) {
return domain.getReferencedContacts().contains(targetResourceRef);
DomainBase domain, Key<ContactResource> targetResourceKey) {
return domain.getReferencedContacts().contains(targetResourceKey);
}
}

View file

@ -30,7 +30,6 @@ import com.google.appengine.tools.mapreduce.ReducerInput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Work;
import google.registry.mapreduce.MapreduceRunner;
import google.registry.mapreduce.inputs.EppResourceInputs;
@ -142,7 +141,7 @@ public abstract class DeleteEppResourceAction<T extends EppResource> implements
}
/** Determine whether the target resource is a linked resource on the domain. */
protected abstract boolean isLinked(DomainBase domain, Ref<T> targetResourceRef);
protected abstract boolean isLinked(DomainBase domain, Key<T> targetResourceKey);
@Override
public void map(DomainBase domain) {
@ -154,12 +153,8 @@ public abstract class DeleteEppResourceAction<T extends EppResource> implements
emit(targetEppResourceKey, false);
return;
}
// The Ref can't be a field on the Mapper, because when a Ref<?> is serialized (required for
// each MapShardTask), it uses the DeadRef version, which contains the Ref's value, which
// isn't serializable. Thankfully, this isn't expensive.
// See: https://github.com/objectify/objectify/blob/master/src/main/java/com/googlecode/objectify/impl/ref/DeadRef.java
if (isActive(domain, targetResourceUpdateTimestamp)
&& isLinked(domain, Ref.create(targetEppResourceKey))) {
&& isLinked(domain, targetEppResourceKey)) {
emit(targetEppResourceKey, true);
}
}

View file

@ -16,7 +16,7 @@ package google.registry.flows.async;
import static google.registry.model.ofy.ObjectifyService.ofy;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.dns.DnsQueue;
import google.registry.model.domain.DomainBase;
import google.registry.model.host.HostResource;
@ -46,8 +46,8 @@ public class DeleteHostResourceAction extends DeleteEppResourceAction<HostResour
private static final long serialVersionUID = 1941092742903217194L;
@Override
protected boolean isLinked(DomainBase domain, Ref<HostResource> targetResourceRef) {
return domain.getNameservers().contains(targetResourceRef);
protected boolean isLinked(DomainBase domain, Key<HostResource> targetResourceKey) {
return domain.getNameservers().contains(targetResourceKey);
}
}
@ -72,7 +72,7 @@ public class DeleteHostResourceAction extends DeleteEppResourceAction<HostResour
if (targetResource.getSuperordinateDomain() != null) {
DnsQueue.create().addHostRefreshTask(targetResource.getFullyQualifiedHostName());
ofy().save().entity(
targetResource.getSuperordinateDomain().get().asBuilder()
ofy().load().key(targetResource.getSuperordinateDomain()).now().asBuilder()
.removeSubordinateHost(targetResource.getFullyQualifiedHostName())
.build());
}

View file

@ -22,7 +22,6 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.appengine.tools.mapreduce.Mapper;
import com.google.common.collect.ImmutableList;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.dns.DnsQueue;
import google.registry.mapreduce.MapreduceRunner;
import google.registry.mapreduce.inputs.EppResourceInputs;
@ -92,7 +91,7 @@ public class DnsRefreshForHostRenameAction implements Runnable {
@Override
public final void map(DomainResource domain) {
if (isActive(domain, hostUpdateTime)
&& domain.getNameservers().contains(Ref.create(targetHostKey))) {
&& domain.getNameservers().contains(targetHostKey)) {
try {
dnsQueue.addDomainRefreshTask(domain.getFullyQualifiedDomainName());
logger.infofmt("Enqueued refresh for domain %s", domain.getFullyQualifiedDomainName());

View file

@ -21,7 +21,6 @@ import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.config.RegistryEnvironment;
import google.registry.flows.EppException;
import google.registry.flows.ResourceAsyncDeleteFlow;
@ -51,7 +50,7 @@ public class ContactDeleteFlow extends ResourceAsyncDeleteFlow<ContactResource,
@Inject ContactDeleteFlow() {}
@Override
protected boolean isLinkedForFailfast(final Ref<ContactResource> ref) {
protected boolean isLinkedForFailfast(final Key<ContactResource> key) {
// Query for the first few linked domains, and if found, actually load them. The query is
// eventually consistent and so might be very stale, but the direct load will not be stale,
// just non-transactional. If we find at least one actual reference then we can reliably
@ -59,11 +58,11 @@ public class ContactDeleteFlow extends ResourceAsyncDeleteFlow<ContactResource,
return Iterables.any(
ofy().load().keys(
queryDomainsUsingResource(
ContactResource.class, ref, now, FAILFAST_CHECK_COUNT)).values(),
ContactResource.class, key, now, FAILFAST_CHECK_COUNT)).values(),
new Predicate<DomainBase>() {
@Override
public boolean apply(DomainBase domain) {
return domain.getReferencedContacts().contains(ref);
return domain.getReferencedContacts().contains(key);
}});
}

View file

@ -23,7 +23,7 @@ import static google.registry.util.CollectionUtils.isNullOrEmpty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.flows.EppException;
import google.registry.flows.EppException.AuthorizationErrorException;
import google.registry.flows.EppException.ObjectDoesNotExistException;
@ -173,7 +173,7 @@ public class DomainAllocateFlow extends DomainCreateOrAllocateFlow {
sunrushAddGracePeriod ? GracePeriodStatus.SUNRUSH_ADD : GracePeriodStatus.ADD,
billingEvent))
.setApplicationTime(allocateCreate.getApplicationTime())
.setApplication(Ref.create(application))
.setApplication(Key.create(application))
.setSmdId(allocateCreate.getSmdId())
.setLaunchNotice(allocateCreate.getNotice());
// Names on the collision list will not be delegated. Set server hold.

View file

@ -19,7 +19,7 @@ import static google.registry.flows.domain.DomainFlowUtils.validateFeeChallenge;
import static google.registry.model.domain.fee.Fee.FEE_CREATE_COMMAND_EXTENSIONS_IN_PREFERENCE_ORDER;
import static google.registry.model.eppoutput.Result.Code.Success;
import static google.registry.model.index.DomainApplicationIndex.loadActiveApplicationsByDomainName;
import static google.registry.model.index.ForeignKeyIndex.loadAndGetReference;
import static google.registry.model.index.ForeignKeyIndex.loadAndGetKey;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
@ -156,7 +156,7 @@ public class DomainApplicationCreateFlow extends BaseDomainCreateFlow<DomainAppl
}
// Fail if the domain is already registered (e.g. this is a landrush application but the domain
// was awarded at the end of sunrise).
if (loadAndGetReference(DomainResource.class, targetId, now) != null) {
if (loadAndGetKey(DomainResource.class, targetId, now) != null) {
throw new ResourceAlreadyExistsException(targetId);
}
}

View file

@ -20,7 +20,7 @@ import static google.registry.util.DateTimeUtils.leapSafeAddYears;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.dns.DnsQueue;
import google.registry.flows.EppException;
import google.registry.model.billing.BillingEvent;
@ -74,8 +74,8 @@ public abstract class DomainCreateOrAllocateFlow
builder
.setRegistrationExpirationTime(registrationExpirationTime)
.setAutorenewBillingEvent(Ref.create(autorenewEvent))
.setAutorenewPollMessage(Ref.create(autorenewPollMessage));
.setAutorenewBillingEvent(Key.create(autorenewEvent))
.setAutorenewPollMessage(Key.create(autorenewPollMessage));
setDomainCreateOrAllocateProperties(builder);
}

View file

@ -114,8 +114,8 @@ public class DomainDeleteFlow extends ResourceSyncDeleteFlow<DomainResource, Bui
.build();
builder.setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE))
.setDeletionTime(deletionTime)
// Clear out all old grace periods and add REDEMPTION, which does not include a ref
// to a billing event because there isn't one for a domain delete.
// Clear out all old grace periods and add REDEMPTION, which does not include a key to a
// billing event because there isn't one for a domain delete.
.setGracePeriods(ImmutableSet.of(GracePeriod.createWithoutBillingEvent(
GracePeriodStatus.REDEMPTION,
now.plus(registry.getRedemptionGracePeriodLength()),
@ -142,11 +142,13 @@ public class DomainDeleteFlow extends ResourceSyncDeleteFlow<DomainResource, Bui
Money cost;
if (gracePeriod.getType() == GracePeriodStatus.AUTO_RENEW) {
TimeOfYear recurrenceTimeOfYear =
checkNotNull(gracePeriod.getRecurringBillingEvent()).get().getRecurrenceTimeOfYear();
ofy().load().key(checkNotNull(gracePeriod.getRecurringBillingEvent())).now()
.getRecurrenceTimeOfYear();
DateTime autoRenewTime = recurrenceTimeOfYear.getLastInstanceBeforeOrAt(now);
cost = getDomainRenewCost(targetId, autoRenewTime, 1);
} else {
cost = checkNotNull(gracePeriod.getOneTimeBillingEvent()).get().getCost();
cost =
ofy().load().key(checkNotNull(gracePeriod.getOneTimeBillingEvent())).now().getCost();
}
creditsBuilder.add(Credit.create(
cost.negated().getAmount(),

View file

@ -40,7 +40,6 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.flows.EppException;
import google.registry.flows.EppException.AuthorizationErrorException;
import google.registry.flows.EppException.ObjectDoesNotExistException;
@ -246,23 +245,23 @@ public class DomainFlowUtils {
/** Verify that no linked resources have disallowed statuses. */
static void verifyNotInPendingDelete(
Set<DesignatedContact> contacts,
Ref<ContactResource> registrant,
Set<Ref<HostResource>> nameservers) throws EppException {
Key<ContactResource> registrant,
Set<Key<HostResource>> nameservers) throws EppException {
for (DesignatedContact contact : nullToEmpty(contacts)) {
verifyNotInPendingDelete(contact.getContactRef());
verifyNotInPendingDelete(contact.getContactKey());
}
if (registrant != null) {
verifyNotInPendingDelete(registrant);
}
for (Ref<HostResource> host : nullToEmpty(nameservers)) {
for (Key<HostResource> host : nullToEmpty(nameservers)) {
verifyNotInPendingDelete(host);
}
}
private static void verifyNotInPendingDelete(
Ref<? extends EppResource> resourceRef) throws EppException {
Key<? extends EppResource> resourceKey) throws EppException {
EppResource resource = resourceRef.get();
EppResource resource = ofy().load().key(resourceKey).now();
if (resource.getStatusValues().contains(StatusValue.PENDING_DELETE)) {
throw new LinkedResourceInPendingDeleteProhibitsOperationException(resource.getForeignKey());
}
@ -302,7 +301,7 @@ public class DomainFlowUtils {
}
static void validateRequiredContactsPresent(
Ref<ContactResource> registrant, Set<DesignatedContact> contacts)
Key<ContactResource> registrant, Set<DesignatedContact> contacts)
throws RequiredParameterMissingException {
if (registrant == null) {
throw new MissingRegistrantException();
@ -446,14 +445,14 @@ public class DomainFlowUtils {
@SuppressWarnings("unchecked")
static void updateAutorenewRecurrenceEndTime(DomainResource domain, DateTime newEndTime) {
Optional<PollMessage.Autorenew> autorenewPollMessage =
Optional.fromNullable(domain.getAutorenewPollMessage().get());
Optional.fromNullable(ofy().load().key(domain.getAutorenewPollMessage()).now());
// Construct an updated autorenew poll message. If the autorenew poll message no longer exists,
// create a new one at the same id. This can happen if a transfer was requested on a domain
// where all autorenew poll messages had already been delivered (this would cause the poll
// message to be deleted), and then subsequently the transfer was canceled, rejected, or deleted
// (which would cause the poll message to be recreated here).
Key<PollMessage.Autorenew> existingAutorenewKey = domain.getAutorenewPollMessage().key();
Key<PollMessage.Autorenew> existingAutorenewKey = domain.getAutorenewPollMessage();
PollMessage.Autorenew updatedAutorenewPollMessage = autorenewPollMessage.isPresent()
? autorenewPollMessage.get().asBuilder().setAutorenewEndTime(newEndTime).build()
: newAutorenewPollMessage(domain)
@ -472,7 +471,7 @@ public class DomainFlowUtils {
ofy().save().entity(updatedAutorenewPollMessage);
}
ofy().save().entity(domain.getAutorenewBillingEvent().get().asBuilder()
ofy().save().entity(ofy().load().key(domain.getAutorenewBillingEvent()).now().asBuilder()
.setRecurrenceEndTime(newEndTime)
.build());
}

View file

@ -30,7 +30,7 @@ import static google.registry.util.DateTimeUtils.leapSafeAddYears;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.flows.EppException;
import google.registry.flows.EppException.ObjectPendingTransferException;
import google.registry.flows.EppException.ParameterValueRangeErrorException;
@ -145,8 +145,8 @@ public class DomainRenewFlow extends OwnedResourceMutateFlow<DomainResource, Ren
ofy().save().<Object>entities(explicitRenewEvent, newAutorenewEvent, newAutorenewPollMessage);
return existingResource.asBuilder()
.setRegistrationExpirationTime(newExpirationTime)
.setAutorenewBillingEvent(Ref.create(newAutorenewEvent))
.setAutorenewPollMessage(Ref.create(newAutorenewPollMessage))
.setAutorenewBillingEvent(Key.create(newAutorenewEvent))
.setAutorenewPollMessage(Key.create(newAutorenewPollMessage))
.addGracePeriod(GracePeriod.forBillingEvent(GracePeriodStatus.RENEW, explicitRenewEvent))
.build();
}

View file

@ -28,7 +28,7 @@ import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.ImmutableList;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.dns.DnsQueue;
import google.registry.flows.EppException;
import google.registry.flows.EppException.CommandUseErrorException;
@ -160,8 +160,8 @@ public class DomainRestoreRequestFlow extends OwnedResourceMutateFlow<DomainReso
.setStatusValues(null)
.setGracePeriods(null)
.setDeletePollMessage(null)
.setAutorenewBillingEvent(Ref.create(autorenewEvent))
.setAutorenewPollMessage(Ref.create(autorenewPollMessage))
.setAutorenewBillingEvent(Key.create(autorenewEvent))
.setAutorenewPollMessage(Key.create(autorenewPollMessage))
.build();
}

View file

@ -25,7 +25,7 @@ import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.flows.EppException;
import google.registry.flows.ResourceTransferApproveFlow;
import google.registry.model.billing.BillingEvent;
@ -127,8 +127,8 @@ public class DomainTransferApproveFlow extends
ofy().save().entity(gainingClientAutorenewPollMessage);
builder
.setRegistrationExpirationTime(newExpirationTime)
.setAutorenewBillingEvent(Ref.create(autorenewEvent))
.setAutorenewPollMessage(Ref.create(gainingClientAutorenewPollMessage))
.setAutorenewBillingEvent(Key.create(autorenewEvent))
.setAutorenewPollMessage(Key.create(gainingClientAutorenewPollMessage))
// Remove all the old grace periods and add a new one for the transfer.
.setGracePeriods(ImmutableSet.of(
GracePeriod.forBillingEvent(GracePeriodStatus.TRANSFER, billingEvent)));

View file

@ -28,7 +28,6 @@ import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.flows.EppException;
import google.registry.flows.ResourceTransferRequestFlow;
import google.registry.model.billing.BillingEvent;
@ -174,9 +173,9 @@ public class DomainTransferRequestFlow
@Override
protected void setTransferDataProperties(TransferData.Builder builder) {
builder
.setServerApproveBillingEvent(Ref.create(transferBillingEvent))
.setServerApproveAutorenewEvent(Ref.create(gainingClientAutorenewEvent))
.setServerApproveAutorenewPollMessage(Ref.create(gainingClientAutorenewPollMessage))
.setServerApproveBillingEvent(Key.create(transferBillingEvent))
.setServerApproveAutorenewEvent(Key.create(gainingClientAutorenewEvent))
.setServerApproveAutorenewPollMessage(Key.create(gainingClientAutorenewPollMessage))
.setExtendedRegistrationYears(command.getPeriod().getValue());
}
@ -208,7 +207,7 @@ public class DomainTransferRequestFlow
.setClientId(existingResource.getCurrentSponsorClientId())
.setEventTime(automaticTransferTime)
.setBillingTime(expirationTime.plus(registry.getAutoRenewGracePeriodLength()))
.setRecurringEventRef(existingResource.getAutorenewBillingEvent())
.setRecurringEventKey(existingResource.getAutorenewBillingEvent())
.setParent(historyEntry)
.build();
ofy().save().entity(autorenewCancellation);

View file

@ -109,7 +109,7 @@ public class DomainUpdateFlow extends BaseDomainUpdateFlow<DomainResource, Build
// occur at the same time as the sunrush add grace period, as the event time will differ
// between them.
BillingEvent.OneTime originalAddEvent =
sunrushAddGracePeriod.get().getOneTimeBillingEvent().get();
ofy().load().key(sunrushAddGracePeriod.get().getOneTimeBillingEvent()).now();
BillingEvent.OneTime billingEvent = new BillingEvent.OneTime.Builder()
.setReason(Reason.CREATE)
.setTargetId(targetId)

View file

@ -23,7 +23,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.CollectionUtils.isNullOrEmpty;
import com.google.common.base.Optional;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.dns.DnsQueue;
import google.registry.flows.EppException;
import google.registry.flows.EppException.ParameterValueRangeErrorException;
@ -64,7 +64,7 @@ public class HostCreateFlow extends ResourceCreateFlow<HostResource, Builder, Cr
* to the actual object creation, which is why this class looks up and stores the superordinate
* domain ahead of time.
*/
private Optional<Ref<DomainResource>> superordinateDomain;
private Optional<Key<DomainResource>> superordinateDomain;
@Inject HostCreateFlow() {}
@ -103,7 +103,7 @@ public class HostCreateFlow extends ResourceCreateFlow<HostResource, Builder, Cr
@Override
protected void modifyCreateRelatedResources() {
if (superordinateDomain.isPresent()) {
ofy().save().entity(superordinateDomain.get().get().asBuilder()
ofy().save().entity(ofy().load().key(superordinateDomain.get()).now().asBuilder()
.addSubordinateHost(command.getFullyQualifiedHostName())
.build());
}

View file

@ -21,7 +21,6 @@ import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.config.RegistryEnvironment;
import google.registry.flows.EppException;
import google.registry.flows.ResourceAsyncDeleteFlow;
@ -51,7 +50,7 @@ public class HostDeleteFlow extends ResourceAsyncDeleteFlow<HostResource, Builde
@Inject HostDeleteFlow() {}
@Override
protected boolean isLinkedForFailfast(final Ref<HostResource> ref) {
protected boolean isLinkedForFailfast(final Key<HostResource> key) {
// Query for the first few linked domains, and if found, actually load them. The query is
// eventually consistent and so might be very stale, but the direct load will not be stale,
// just non-transactional. If we find at least one actual reference then we can reliably
@ -59,11 +58,11 @@ public class HostDeleteFlow extends ResourceAsyncDeleteFlow<HostResource, Builde
return Iterables.any(
ofy().load().keys(
queryDomainsUsingResource(
HostResource.class, ref, now, FAILFAST_CHECK_COUNT)).values(),
HostResource.class, key, now, FAILFAST_CHECK_COUNT)).values(),
new Predicate<DomainBase>() {
@Override
public boolean apply(DomainBase domain) {
return domain.getNameservers().contains(ref);
return domain.getNameservers().contains(key);
}});
}

View file

@ -16,13 +16,14 @@ package google.registry.flows.host;
import static google.registry.model.EppResourceUtils.isActive;
import static google.registry.model.EppResourceUtils.loadByUniqueId;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.registry.Registries.findTldForName;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Key;
import google.registry.flows.EppException;
import google.registry.flows.EppException.AuthorizationErrorException;
import google.registry.flows.EppException.ObjectDoesNotExistException;
@ -75,7 +76,7 @@ public class HostFlowUtils {
}
/** Return the {@link DomainResource} this host is subordinate to, or null for external hosts. */
static Ref<DomainResource> lookupSuperordinateDomain(
static Key<DomainResource> lookupSuperordinateDomain(
InternetDomainName hostName, DateTime now) throws EppException {
Optional<InternetDomainName> tldParsed = findTldForName(hostName);
if (!tldParsed.isPresent()) {
@ -91,7 +92,7 @@ public class HostFlowUtils {
if (superordinateDomain == null || !isActive(superordinateDomain, now)) {
throw new SuperordinateDomainDoesNotExistException(domainName);
}
return Ref.create(superordinateDomain);
return Key.create(superordinateDomain);
}
/** Superordinate domain for this hostname does not exist. */
@ -103,10 +104,11 @@ public class HostFlowUtils {
/** Ensure that the superordinate domain is sponsored by the provided clientId. */
static void verifyDomainIsSameRegistrar(
Ref<DomainResource> superordinateDomain,
Key<DomainResource> superordinateDomain,
String clientId) throws EppException {
if (superordinateDomain != null
&& !clientId.equals(superordinateDomain.get().getCurrentSponsorClientId())) {
&& !clientId.equals(
ofy().load().key(superordinateDomain).now().getCurrentSponsorClientId())) {
throw new HostDomainNotOwnedException();
}
}

View file

@ -18,13 +18,12 @@ import static com.google.common.base.MoreObjects.firstNonNull;
import static google.registry.flows.host.HostFlowUtils.lookupSuperordinateDomain;
import static google.registry.flows.host.HostFlowUtils.validateHostName;
import static google.registry.flows.host.HostFlowUtils.verifyDomainIsSameRegistrar;
import static google.registry.model.index.ForeignKeyIndex.loadAndGetReference;
import static google.registry.model.index.ForeignKeyIndex.loadAndGetKey;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.CollectionUtils.isNullOrEmpty;
import com.google.common.collect.ImmutableMap;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import google.registry.dns.DnsQueue;
import google.registry.flows.EppException;
import google.registry.flows.EppException.ObjectAlreadyExistsException;
@ -63,7 +62,7 @@ import org.joda.time.Duration;
*/
public class HostUpdateFlow extends ResourceUpdateFlow<HostResource, Builder, Update> {
private Ref<DomainResource> superordinateDomain;
private Key<DomainResource> superordinateDomain;
private String oldHostName;
private String newHostName;
@ -85,7 +84,7 @@ public class HostUpdateFlow extends ResourceUpdateFlow<HostResource, Builder, Up
protected void verifyUpdateIsAllowed() throws EppException {
verifyDomainIsSameRegistrar(superordinateDomain, getClientId());
if (isHostRename
&& loadAndGetReference(HostResource.class, newHostName, now) != null) {
&& loadAndGetKey(HostResource.class, newHostName, now) != null) {
throw new HostAlreadyExistsException(newHostName);
}
}
@ -170,24 +169,25 @@ public class HostUpdateFlow extends ResourceUpdateFlow<HostResource, Builder, Up
}
private void updateSuperordinateDomains() {
Ref<DomainResource> oldSuperordinateDomain = existingResource.getSuperordinateDomain();
Key<DomainResource> oldSuperordinateDomain = existingResource.getSuperordinateDomain();
if (oldSuperordinateDomain != null || superordinateDomain != null) {
if (Objects.equals(oldSuperordinateDomain, superordinateDomain)) {
ofy().save().entity(oldSuperordinateDomain.get().asBuilder()
.removeSubordinateHost(oldHostName)
.addSubordinateHost(newHostName)
.build());
ofy().save().entity(
ofy().load().key(oldSuperordinateDomain).now().asBuilder()
.removeSubordinateHost(oldHostName)
.addSubordinateHost(newHostName)
.build());
} else {
if (oldSuperordinateDomain != null) {
ofy().save().entity(
oldSuperordinateDomain.get()
ofy().load().key(oldSuperordinateDomain).now()
.asBuilder()
.removeSubordinateHost(oldHostName)
.build());
}
if (superordinateDomain != null) {
ofy().save().entity(
superordinateDomain.get()
ofy().load().key(superordinateDomain).now()
.asBuilder()
.addSubordinateHost(newHostName)
.build());