Skip to content

Commit

Permalink
Update purge domain strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
asein-sinch committed Dec 12, 2024
1 parent 276878e commit 68c14c5
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 108 deletions.
11 changes: 5 additions & 6 deletions examples/simple-examples/src/mailgun/emails/purgeDomainQueues.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { getMailgunDomainFromConfig, initMailgunService, printFullResponse } from '../../config';
import { MailgunStorageRegion } from '@sinch/sdk-client';

(async () => {
console.log('*********************');
console.log('* PurgeDomainQueues *');
console.log('*********************');
console.log('********************');
console.log('* PurgeDomainQueue *');
console.log('********************');

const domainName = getMailgunDomainFromConfig();

const mailgunService = initMailgunService();
let response;
try {
response = await mailgunService.emails.purgeDomainQueues(domainName, MailgunStorageRegion.US);
response = await mailgunService.emails.purgeDomainQueue(domainName, 'https://storage-us-west1.api.mailgun.net');
} catch (error) {
console.error('Error when trying to purge the domain queues');
console.error('Error when trying to purge the domain queue');
throw error;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
SendEmailRequest,
SendMimeEmailRequest,
} from '../../../models';
import { MailgunStorageRegion } from '@sinch/sdk-client';
import { MailgunStorageHostname } from '@sinch/sdk-client';

export class EmailsApiFixture implements Partial<Readonly<EmailsApi>> {
/**
Expand All @@ -23,9 +23,9 @@ export class EmailsApiFixture implements Partial<Readonly<EmailsApi>> {
*/
public getStoredEmail: jest.Mock<Promise<GetStoredEmailResponse>, [string, string]> = jest.fn();
/**
* Fixture associated to function purgeDomainQueues
* Fixture associated to function purgeDomainQueue
*/
public purgeDomainQueues: jest.Mock<Promise<GenericResponse>, [string, MailgunStorageRegion]> = jest.fn();
public purgeDomainQueue: jest.Mock<Promise<GenericResponse>, [string, MailgunStorageHostname]> = jest.fn();
/**
* Fixture associated to function getSendingQueuesStatus
*/
Expand Down
61 changes: 8 additions & 53 deletions packages/mailgun/src/rest/v1/emails/emails-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ import {
import {
RequestBody,
SinchClientParameters,
MailgunStorageRegion,
MAILGUN_STORAGE_HOSTNAMES_US,
MAILGUN_STORAGE_HOSTNAMES_EUROPE,
MailgunStorageHostname,
} from '@sinch/sdk-client';
import { MailgunDomainApi } from '../mailgun-domain-api';

Expand Down Expand Up @@ -49,6 +47,7 @@ export class EmailsApi extends MailgunDomainApi {
const getParams = this.client.extractQueryParams<SendEmailRequest>(request, [] as never[]);
const headers: { [key: string]: string | undefined } = {
Accept: 'application/json',
'Content-Type': 'multipart/form-data; charset=utf-8',
};
const body: RequestBody = transformSendEmailRequestIntoApiRequestBody(request);
const basePathUrl = `${this.client.apiClientOptions.hostname}/v3/${domainName}/messages`;
Expand Down Expand Up @@ -129,52 +128,12 @@ export class EmailsApi extends MailgunDomainApi {
*
* The storage hosts are `storage-us-east4.api.mailgun.net`, `storage-us-west1.api.mailgun.net`, and `storage-europe-west1.api.mailgun.net`.
* @param { string } domainName - The name of the domain you want to delete envelope from
* @param { MailgunStorageRegion } storageRegion - The region where the domain is defined (us or europe)
* @param { MailgunStorageHostname } storageHostname - The storage hostname to be purged
*/
public async purgeDomainQueues(domainName: string, storageRegion: MailgunStorageRegion): Promise<GenericResponse> {
let storagesToPurge: string[];
if (storageRegion === MailgunStorageRegion.US) {
storagesToPurge = [
...MAILGUN_STORAGE_HOSTNAMES_US,
...this.storageHostnames,
];
} else if (storageRegion === MailgunStorageRegion.EUROPE) {
storagesToPurge = [
...MAILGUN_STORAGE_HOSTNAMES_EUROPE,
...this.storageHostnames,
];
} else {
console.warn(`Trying to purge the queues for the domain '${domainName}' on an unsupported region: '${storageRegion}'`);
storagesToPurge = [
...this.storageHostnames,
];
}
const requests = storagesToPurge.map((hostname) =>
this.purgeStorageQueue(hostname, domainName)
.then((response) => {
return { hostname, response };
})
.catch(() => {
console.log(`Request failed at: ${hostname}`);
return null;
}),
);

const results = await Promise.allSettled(requests);

const successfulResponses = results
.filter((result) => result.status === 'fulfilled' && result.value)
.map((result) => (result as PromiseFulfilledResult<{ hostname: string; response: GenericResponse }>).value);

if (successfulResponses.length > 0) {
successfulResponses.forEach(({ hostname }) => console.log(`Domain queue successfully purged at: ${hostname}`));
return successfulResponses[0].response;
} else {
throw new Error('All requests failed. Domain may not exist in any region.');
}
}

public async purgeStorageQueue(storageHostname: string, domainName: string): Promise<GenericResponse> {
public async purgeDomainQueue(
domainName: string,
storageHostname: MailgunStorageHostname,
): Promise<GenericResponse> {
this.client = this.getSinchClient();
const getParams = {};
const headers: { [key: string]: string | undefined } = {
Expand All @@ -197,7 +156,7 @@ export class EmailsApi extends MailgunDomainApi {
url,
requestOptions,
apiName: this.apiName,
operationId: 'purgeDomainQueues',
operationId: 'purgeDomainQueue',
});

return transformGenericResponseIntoClientResponse(apiResponse);
Expand Down Expand Up @@ -231,8 +190,4 @@ export class EmailsApi extends MailgunDomainApi {
return transformSendingQueuesStatusResponseIntoClientResponse(apiResponse);
}

public setStorageHostnames(storageHostnames: string[]) {
this.storageHostnames = storageHostnames;
}

}
7 changes: 0 additions & 7 deletions packages/mailgun/src/rest/v1/mailgun-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,4 @@ export class MailgunService {
this.emails.setHostname(hostname);
}

/**
* Update the default hostname to purge the emails queues
* @param {string} storageHostnames - The new hostnames for the emails storage.
*/
public setStorageHostnames(storageHostnames: string[]) {
this.emails.setStorageHostnames(storageHostnames);
}
}
12 changes: 6 additions & 6 deletions packages/mailgun/tests/rest/v1/emails/emails-api.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MailgunCredentials, MailgunStorageRegion } from '@sinch/sdk-client';
import { MailgunCredentials, MailgunStorageHostname } from '@sinch/sdk-client';
import { EmailsApi, EmailsApiFixture } from '../../../../src';
import {
sendEmailRequestWithHtml,
Expand Down Expand Up @@ -77,16 +77,16 @@ describe('EmailsApi', () => {
it('should make a DELETE request to purge the domain queues', async () => {
// Given
const domainName: string = 'domainName';
const storageRegion = MailgunStorageRegion.US;
const storageHostname: MailgunStorageHostname = 'storageHostname';

// When
fixture.purgeDomainQueues.mockResolvedValue(genericResponse);
emailsApi.purgeDomainQueues = fixture.purgeDomainQueues;
const response = await emailsApi.purgeDomainQueues(domainName, storageRegion);
fixture.purgeDomainQueue.mockResolvedValue(genericResponse);
emailsApi.purgeDomainQueue = fixture.purgeDomainQueue;
const response = await emailsApi.purgeDomainQueue(domainName, storageHostname);

// Then
expect(response).toEqual(genericResponse);
expect(fixture.purgeDomainQueues).toHaveBeenCalledWith(domainName, storageRegion);
expect(fixture.purgeDomainQueue).toHaveBeenCalledWith(domainName, storageHostname);
});
});

Expand Down
5 changes: 2 additions & 3 deletions packages/mailgun/tests/rest/v1/emails/emails.steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Given('the Mailgun service "Emails" is available', () => {

When('I send a request to send a text email', async () => {
sendEmailResponse = await emailsApi.sendEmail(domainName, {
from: 'Excited E2E user <[email protected]>',
from: 'Excited E2E user ✉️ <[email protected]>',
to: '[email protected]',
subject: 'E2E test text email',
text: 'Hello, this is a text message for E2E testing.',
Expand Down Expand Up @@ -107,8 +107,7 @@ Then('the response contains the sending queues status', () => {
});

When('I send a request to purge the domain queues', async () => {
emailsApi.setStorageHostnames(['http://localhost:3021']);
purgeDomainQueuesResponse = await emailsApi.purgeDomainQueues(domainName, 'anyRegion');
purgeDomainQueuesResponse = await emailsApi.purgeDomainQueue(domainName, 'http://localhost:3021');
});

Then('the response indicates the purge has been done', () => {
Expand Down
12 changes: 0 additions & 12 deletions packages/mailgun/tests/rest/v1/mailgun-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ import { EmailsApi, MailgunService } from '../../../src';
describe('Mailgun Service', () => {

const CUSTOM_HOSTNAME = 'https://new.host.name';
const CUSTOM_STORAGE_HOSTNAMES = [
'https://new-region.storage.name',
'https://other-region.storage.name',
];
let params: SinchClientParameters;

beforeEach(() => {
Expand All @@ -33,12 +29,4 @@ describe('Mailgun Service', () => {
expect(mailgunService.emails.getSinchClient().apiClientOptions.hostname).toBe(CUSTOM_HOSTNAME);
});

it('should set custom storage hostnames', () => {
// When
const mailgunService = new MailgunService(params);
mailgunService.setStorageHostnames(CUSTOM_STORAGE_HOSTNAMES);

// Then
expect(mailgunService.emails.storageHostnames).toBe(CUSTOM_STORAGE_HOSTNAMES);
});
});
12 changes: 5 additions & 7 deletions packages/sdk-client/src/domain/domain-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ export const CONVERSATION_TEMPLATES_HOSTNAME = `https://${REGION_PATTERN}templat
export const ELASTIC_SIP_TRUNKING_HOSTNAME = 'https://elastic-trunking.api.sinch.com';
export const FAX_HOSTNAME = `https://${REGION_PATTERN}fax.api.sinch.com`;
export const MAILGUN_HOSTNAME = `https://api.${REGION_PATTERN}mailgun.net`;
export const MAILGUN_STORAGE_HOSTNAMES_US = [
'https://storage-us-east4.api.mailgun.net',
'https://storage-us-west1.api.mailgun.net',
];
export const MAILGUN_STORAGE_HOSTNAMES_EUROPE = [
'https://storage-europe-west1.api.mailgun.net',
];
export type MailgunStorageHostname =
'https://storage-us-east4.api.mailgun.net'
| 'https://storage-us-west1.api.mailgun.net'
| 'https://storage-europe-west1.api.mailgun.net'
| string;
export const NUMBERS_HOSTNAME = 'https://numbers.api.sinch.com';
export const SMS_HOSTNAME = `https://${REGION_PATTERN}sms.api.sinch.com`;
export const VERIFICATION_HOSTNAME = 'https://verification.api.sinch.com';
Expand Down
11 changes: 0 additions & 11 deletions packages/sdk-client/src/domain/domain-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,14 +181,3 @@ export type MailgunRegion = SupportedMailgunRegion | string;
export const MailgunRegion = {
...SupportedMailgunRegion,
};

export enum SupportedMailgunStorageRegion {
US,
EUROPE
}

export type MailgunStorageRegion = SupportedMailgunStorageRegion | string;

export const MailgunStorageRegion = {
...SupportedMailgunStorageRegion,
};

0 comments on commit 68c14c5

Please sign in to comment.