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

Add dual-write for RegistrarPoc #484

Closed
Closed
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
@@ -0,0 +1,89 @@
// Copyright 2020 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.schema.registrar;

import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;

import google.registry.model.registrar.RegistrarContact;
import java.util.Optional;

/** Data access object for {@link RegistrarContact}. */
public class RegistrarPocDao {
private RegistrarPocDao() {}

/** Persists a new registrar POC in Cloud SQL. */
public static void saveNew(RegistrarContact registrarPoc) {
checkArgumentNotNull(registrarPoc, "registrarPoc must be specified");
jpaTm().transact(() -> jpaTm().getEntityManager().persist(registrarPoc));
}

/** Updates an existing registrar POC in Cloud SQL, throws exception if it does not exist. */
public static void update(RegistrarContact registrarPoc) {
checkArgumentNotNull(registrarPoc, "registrarPoc must be specified");
jpaTm()
.transact(
() -> {
checkArgument(
checkExists(registrarPoc.getEmailAddress()),
"A registrar POC of this email address does not exist: %s.",
registrarPoc.getEmailAddress());
jpaTm().getEntityManager().merge(registrarPoc);
});
}

/** Returns whether the registrar POC of the given email address exists. */
public static boolean checkExists(String emailAddress) {
checkArgumentNotNull(emailAddress, "emailAddress must be specified");
return jpaTm()
.transact(
() ->
jpaTm()
.getEntityManager()
.createQuery(
"SELECT 1 FROM RegistrarContact WHERE emailAddress = :emailAddress",
Integer.class)
.setParameter("emailAddress", emailAddress)
.setMaxResults(1)
.getResultList()
.size()
> 0);
}

/** Loads the registrar POC by its id, returns empty if it doesn't exist. */
public static Optional<RegistrarContact> load(String emailAddress) {
checkArgumentNotNull(emailAddress, "emailAddress must be specified");
return Optional.ofNullable(
jpaTm()
.transact(() -> jpaTm().getEntityManager().find(RegistrarContact.class, emailAddress)));
}

/** Deletes the registrar POC by its id, throws exception if it doesn't exist. */
public static void delete(String emailAddress) {
checkArgumentNotNull(emailAddress, "emailAddress must be specified");
jpaTm()
.transact(
() ->
jpaTm()
.getEntityManager()
.remove(
checkArgumentPresent(
load(emailAddress),
"A registrar POC of this email address does not exist: %s.",
emailAddress)));
}
}
Expand Up @@ -18,6 +18,7 @@
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.util.CollectionUtils.nullToEmpty;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
Expand All @@ -29,9 +30,11 @@
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger;
import google.registry.model.common.GaeUserIdConverter;
import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact;
import google.registry.schema.registrar.RegistrarPocDao;
import google.registry.tools.params.OptionalPhoneNumberParameter;
import google.registry.tools.params.PathParameter;
import java.io.IOException;
Expand All @@ -53,6 +56,8 @@
commandDescription = "Create/read/update/delete the various contact lists for a Registrar.")
final class RegistrarContactCommand extends MutatingCommand {

static final FluentLogger logger = FluentLogger.forEnclosingClass();

@Parameter(
description = "Client identifier of the registrar account.",
required = true)
Expand Down Expand Up @@ -153,6 +158,8 @@ enum Mode { LIST, CREATE, UPDATE, DELETE }

@Nullable
private ImmutableSet<RegistrarContact.Type> contactTypes;
private RegistrarContact oldContact;
private RegistrarContact newContact;

@Override
protected void init() throws Exception {
Expand Down Expand Up @@ -185,13 +192,13 @@ protected void init() throws Exception {
for (RegistrarContact rc : contacts) {
contactsMap.put(rc.getEmailAddress(), rc);
}
RegistrarContact oldContact;
switch (mode) {
case LIST:
listContacts(contacts);
break;
case CREATE:
stageEntityChange(null, createContact(registrar));
newContact = createContact(registrar);
stageEntityChange(null, newContact);
if ((visibleInDomainWhoisAsAbuse != null) && visibleInDomainWhoisAsAbuse) {
unsetOtherWhoisAbuseFlags(contacts, null);
}
Expand All @@ -202,7 +209,7 @@ protected void init() throws Exception {
contactsMap.get(checkNotNull(email, "--email is required when --mode=UPDATE")),
"No contact with the given email: %s",
email);
RegistrarContact newContact = updateContact(oldContact, registrar);
newContact = updateContact(oldContact, registrar);
checkArgument(
!oldContact.getVisibleInDomainWhoisAsAbuse()
|| newContact.getVisibleInDomainWhoisAsAbuse(),
Expand Down Expand Up @@ -232,6 +239,39 @@ protected void init() throws Exception {
}
}

@Override
protected String execute() throws Exception {
// Save registrarPoc to Datastore and output its response
logger.atInfo().log(super.execute());

String cloudSqlMessage;
try {
jpaTm()
.transact(
() -> {
switch (mode) {
case CREATE:
RegistrarPocDao.saveNew(newContact);
break;
case UPDATE:
RegistrarPocDao.update(newContact);
break;
case DELETE:
RegistrarPocDao.delete(oldContact.getEmailAddress());
break;
default:
throw new AssertionError(String.format("Unknown mode: ", mode.name()));
}
});
cloudSqlMessage = "Updated the registrar POC in Cloud SQL.\n";
} catch (Throwable t) {
cloudSqlMessage =
"Unexpected error saving registrar POC to Cloud SQL from nomulus tool command";
logger.atSevere().withCause(t).log(cloudSqlMessage);
}
return cloudSqlMessage;
}

private void listContacts(Set<RegistrarContact> contacts) throws IOException {
List<String> result = new ArrayList<>();
for (RegistrarContact c : contacts) {
Expand Down
Expand Up @@ -19,12 +19,14 @@
import google.registry.model.registry.RegistryLockDaoTest;
import google.registry.persistence.transaction.JpaEntityCoverage;
import google.registry.schema.cursor.CursorDaoTest;
import google.registry.schema.registrar.RegistrarPocDaoTest;
import google.registry.schema.tld.PremiumListDaoTest;
import google.registry.schema.tld.ReservedListDaoTest;
import google.registry.schema.tmch.ClaimsListDaoTest;
import google.registry.tools.CreateReservedListCommandTest;
import google.registry.tools.DomainLockUtilsTest;
import google.registry.tools.LockDomainCommandTest;
import google.registry.tools.RegistrarContactCommandTest;
import google.registry.tools.UnlockDomainCommandTest;
import google.registry.tools.UpdateReservedListCommandTest;
import google.registry.tools.server.CreatePremiumListActionTest;
Expand Down Expand Up @@ -59,6 +61,8 @@
LockDomainCommandTest.class,
DomainBaseSqlTest.class,
PremiumListDaoTest.class,
RegistrarContactCommandTest.class,
RegistrarPocDaoTest.class,
RegistryLockDaoTest.class,
RegistryLockGetActionTest.class,
RegistryLockVerifyActionTest.class,
Expand Down
@@ -0,0 +1,97 @@
// Copyright 2020 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.schema.registrar;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static org.junit.Assert.assertThrows;

import google.registry.model.EntityTestCase;
import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.testing.FakeClock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link RegistrarPocDao}. */
@RunWith(JUnit4.class)
public class RegistrarPocDaoTest extends EntityTestCase {
private final FakeClock fakeClock = new FakeClock();

@Rule
public final JpaTestRules.JpaIntegrationWithCoverageRule jpaRule =
new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationWithCoverageRule();

private Registrar testRegistrar;
private RegistrarContact testRegistrarContact;

@Before
public void setUp() {
testRegistrar = loadRegistrar("TheRegistrar");
testRegistrarContact =
new RegistrarContact.Builder()
.setParent(testRegistrar)
.setEmailAddress("contact@registrar.google")
.setName("theRegistrarPoc")
.build();
}

@Test
public void saveNew_worksSuccessfully() {
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isFalse();
RegistrarPocDao.saveNew(testRegistrarContact);
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isTrue();
}

@Test
public void update_worksSuccessfully() {
RegistrarPocDao.saveNew(testRegistrarContact);
RegistrarContact persisted = RegistrarPocDao.load("contact@registrar.google").get();
assertThat(persisted.getName()).isEqualTo("theRegistrarPoc");
RegistrarPocDao.update(
persisted.asBuilder().setParent(testRegistrar).setName("newRegistrarPoc").build());
persisted = RegistrarPocDao.load("contact@registrar.google").get();
assertThat(persisted.getName()).isEqualTo("newRegistrarPoc");
}

@Test
public void update_throwsExceptionWhenEntityDoesNotExist() {
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isFalse();
assertThrows(
IllegalArgumentException.class, () -> RegistrarPocDao.update(testRegistrarContact));
}

@Test
public void load_worksSuccessfully() {
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isFalse();
RegistrarPocDao.saveNew(testRegistrarContact);
RegistrarContact persisted = RegistrarPocDao.load("contact@registrar.google").get();

assertThat(persisted.getEmailAddress()).isEqualTo("contact@registrar.google");
assertThat(persisted.getName()).isEqualTo("theRegistrarPoc");
}

@Test
public void delete_worksSuccessfully() {
RegistrarPocDao.saveNew(testRegistrarContact);
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isTrue();
RegistrarPocDao.delete("contact@registrar.google");
assertThat(RegistrarPocDao.checkExists("contact@registrar.google")).isFalse();
}
}