Skip to content
This repository was archived by the owner on Jun 28, 2022. It is now read-only.

Commit

Permalink
fix: subfolders redirect (#60)
Browse files Browse the repository at this point in the history
* fix: subfolders redirect

* chore: remove website deploy for a while
  • Loading branch information
arantespp authored May 22, 2022
1 parent 52fad8e commit 92de986
Show file tree
Hide file tree
Showing 9 changed files with 2,247 additions and 3,369 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,5 @@ package-lock.json

github-app/
.npmrc
.carlin/
.carlin/
.vscode
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ScheduledHandler } from 'aws-lambda';

import { executeTasks } from './executeTasks';

/**
* Update CI/CD resources with the newest carlin and repository image.
*/
export const imageUpdaterScheduleHandler: ScheduledHandler = async () => {
const cicdConfig = process.env.CICD_CONFIG;

if (!cicdConfig) {
console.log('No CICD config found.');
return;
}

Expand All @@ -23,7 +24,7 @@ export const imageUpdaterScheduleHandler: ScheduledHandler = async () => {
`carlin deploy cicd -c carlin.json`,
];

const response = await executeTasks({
await executeTasks({
commands,
cpu: '512',
memory: '2048',
Expand All @@ -34,6 +35,4 @@ export const imageUpdaterScheduleHandler: ScheduledHandler = async () => {
},
],
});

console.log(JSON.stringify(response, null, 2));
};
10 changes: 4 additions & 6 deletions packages/cli/src/deploy/cicd/lambdas/pipelines.handler.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import AdmZip from 'adm-zip';
import { CodePipelineEvent, CodePipelineHandler } from 'aws-lambda';
import { CodePipeline, S3 } from 'aws-sdk';
import * as fs from 'fs';

import { CodePipeline, S3 } from 'aws-sdk';
import { CodePipelineEvent, CodePipelineHandler } from 'aws-lambda';
import { Pipeline, getMainCommands, getTagCommands } from '../pipelines';

import { executeTasks, shConditionalCommands } from './executeTasks';
import { putApprovalResultManualTask } from './putApprovalResultManualTask';
import AdmZip from 'adm-zip';

const codepipeline = new CodePipeline();

Expand Down Expand Up @@ -37,7 +35,7 @@ export const getJobDetails = async (event: CodePipelineEvent) => {

if (!Body) {
throw new Error(
'Cannot retrieve the job description (there is no input artifact).',
'Cannot retrieve the job description (there is no input artifact).'
);
}

Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/deploy/cicd/pipelines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export const getMainCommands = () => [
/**
* Reporting `MainTagFound` before exiting the process. This command blocks
* the process if tag was found. If we don't do this, the loop would never
* end.
* end because `main` command can create a tag, that would trigger this
* pipeline again.
*/
'if git describe --exact-match; then echo "Tag found" && carlin cicd-ecs-task-report --status=MainTagFound && exit 0; fi',
'yarn',
Expand Down
21 changes: 19 additions & 2 deletions packages/cli/src/deploy/staticApp/staticApp.template.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,32 @@ import { faker } from '@ttoss/test-utils/faker';

const region = faker.random.word();

test('should define default root object', () => {
const template = getStaticAppTemplate({ region, cloudfront: true });
test('should define default root object for spa', () => {
const template = getStaticAppTemplate({
region,
cloudfront: true,
spa: true,
});

expect(
template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties
.DistributionConfig.DefaultRootObject
).toEqual('index.html');
});

test('should define default root object as undefined for not spa', () => {
const template = getStaticAppTemplate({
region,
cloudfront: true,
spa: false,
});

expect(
template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties
.DistributionConfig.DefaultRootObject
).toEqual(undefined);
});

test('should not add CloudFront distribution', () => {
const template = getStaticAppTemplate({ region, cloudfront: false });

Expand Down
85 changes: 26 additions & 59 deletions packages/cli/src/deploy/staticApp/staticApp.template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,16 @@ const STATIC_APP_BUCKET_LOGICAL_ID = 'StaticBucket';

const CLOUDFRONT_DISTRIBUTION_ID = 'CloudFrontDistributionId';

const CLOUDFRONT_DISTRIBUTION_ORIGIN_ACCESS_IDENTITY_LOGICAL_ID =
'CloudFrontDistributionOriginAccessIdentity';

export const CLOUDFRONT_DISTRIBUTION_LOGICAL_ID = 'CloudFrontDistribution';

export const ROUTE_53_RECORD_SET_GROUP_LOGICAL_ID = 'Route53RecordSetGroup';

/**
* Name: Managed-CachingOptimized
* ID: 658327ea-f89d-4fab-a63d-7e88639e58f6
* Name: Managed-CachingDisabled
* ID: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html
*/
const CACHE_POLICY_ID = '658327ea-f89d-4fab-a63d-7e88639e58f6';
const CACHE_POLICY_ID = '4135ea2d-6df8-44a3-9df3-4b5a84be39ad';

/**
* Name: Managed-CORS-S3Origin
Expand All @@ -41,7 +38,6 @@ const ORIGIN_REQUEST_POLICY_ID = '88a5eaf4-2fd4-4709-b370-b4c650ea3fcf';
const ORIGIN_RESPONSE_POLICY_ID = 'eaab4381-ed33-4a86-88ca-d9558dc6cd63';

const getBaseTemplate = ({
cloudfront,
spa,
}: {
cloudfront?: boolean;
Expand All @@ -66,7 +62,7 @@ const getBaseTemplate = ({
},
WebsiteConfiguration: {
IndexDocument: `index.html`,
ErrorDocument: `${spa ? 'index' : '404'}.html`,
ErrorDocument: spa ? 'index.html' : '404/index.html',
},
},
},
Expand All @@ -79,6 +75,7 @@ const getBaseTemplate = ({
{
Action: ['s3:GetObject'],
Effect: 'Allow',
Principal: '*',
Resource: {
'Fn::Join': [
'',
Expand All @@ -89,23 +86,6 @@ const getBaseTemplate = ({
],
],
},
Principal: cloudfront
? /**
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
*/
{
AWS: {
'Fn::Sub': [
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${OAI}',
{
OAI: {
Ref: CLOUDFRONT_DISTRIBUTION_ORIGIN_ACCESS_IDENTITY_LOGICAL_ID,
},
},
],
},
}
: '*',
},
],
},
Expand Down Expand Up @@ -141,19 +121,6 @@ const getCloudFrontTemplate = ({
const template = { ...getBaseTemplate({ cloudfront, spa }) };

const cloudFrontResources: { [key: string]: Resource } = {
[CLOUDFRONT_DISTRIBUTION_ORIGIN_ACCESS_IDENTITY_LOGICAL_ID]: {
Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity',
Properties: {
CloudFrontOriginAccessIdentityConfig: {
Comment: {
'Fn::Sub': [
'CloudFront Distribution Origin Access Identity for ${Project} project.',
{ Project: { Ref: 'Project' } },
],
},
},
},
},
[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID]: {
Type: 'AWS::CloudFront::Distribution',
Properties: {
Expand All @@ -178,17 +145,17 @@ const getCloudFrontTemplate = ({
ErrorCachingMinTTL: 0,
ErrorCode: errorCode,
ResponseCode: 404,
ResponsePagePath: '/404.html',
ResponsePagePath: '/404',
};
}),
DefaultCacheBehavior: {
AllowedMethods: ['GET', 'HEAD', 'OPTIONS'],
Compress: true,
CachedMethods: ['GET', 'HEAD', 'OPTIONS'],
/**
* Caching OPTIONS. Related to OriginRequestPolicyId property.
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-cors
*/
CachedMethods: ['GET', 'HEAD', 'OPTIONS'],
OriginRequestPolicyId: ORIGIN_REQUEST_POLICY_ID,
/**
* CachePolicyId property:
Expand All @@ -199,20 +166,34 @@ const getCloudFrontTemplate = ({
TargetOriginId: { Ref: STATIC_APP_BUCKET_LOGICAL_ID },
ViewerProtocolPolicy: 'redirect-to-https',
},
DefaultRootObject: 'index.html',
DefaultRootObject: spa ? 'index.html' : undefined,
Enabled: true,
HttpVersion: 'http2',
Origins: [
{
CustomOriginConfig: {
OriginProtocolPolicy: 'http-only',
},
/**
* Amazon S3 bucket – awsexamplebucket.s3.us-west-2.amazonaws.com
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName
* https://github.com/aws/aws-cdk/issues/1882#issuecomment-629141467
*/
DomainName: {
'Fn::GetAtt': `${STATIC_APP_BUCKET_LOGICAL_ID}.RegionalDomainName`,
'Fn::Select': [
1,
{
'Fn::Split': [
'//',
{
'Fn::GetAtt': [
STATIC_APP_BUCKET_LOGICAL_ID,
'WebsiteURL',
],
},
],
},
],
},
Id: { Ref: STATIC_APP_BUCKET_LOGICAL_ID },
OriginPath: `/${PACKAGE_VERSION}`,
/**
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html#choose-origin-shield-region
*/
Expand All @@ -222,20 +203,6 @@ const getCloudFrontTemplate = ({
OriginShieldRegion: getOriginShieldRegion(region),
},
}),
S3OriginConfig: {
OriginAccessIdentity: {
'Fn::Join': [
'/',
[
'origin-access-identity',
'cloudfront',
{
Ref: CLOUDFRONT_DISTRIBUTION_ORIGIN_ACCESS_IDENTITY_LOGICAL_ID,
},
],
],
},
},
},
],
},
Expand Down
16 changes: 4 additions & 12 deletions packages/cli/src/deploy/staticApp/uploadBuiltAppToS3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,33 @@ import {
getAllFilesInsideADirectory,
uploadDirectoryToS3,
} from '../s3';
import { getPackageVersion } from '../../utils';

export const uploadBuiltAppToS3 = async ({
buildFolder: directory,
bucket,
cloudfront,
}: {
buildFolder?: string;
bucket: string;
cloudfront?: boolean;
}) => {
const version = cloudfront ? getPackageVersion() : undefined;

/**
* Only empty directory if the number of the files inside $directory.
* If the number of files is zero, uploadDirectoryToS3 will thrown.
*/
if (directory) {
const files = await getAllFilesInsideADirectory({ directory });
if (files.length > 0) {
await emptyS3Directory({ bucket, directory: version });
await emptyS3Directory({ bucket });
}
await uploadDirectoryToS3({ bucket, bucketKey: version, directory });
await uploadDirectoryToS3({ bucket, directory });
return;
}

const defaultDirectory = await findDefaultBuildFolder();

if (defaultDirectory) {
await emptyS3Directory({ bucket, directory: version });
await uploadDirectoryToS3({
bucket,
bucketKey: version,
directory: defaultDirectory,
});
await emptyS3Directory({ bucket });
await uploadDirectoryToS3({ bucket, directory: defaultDirectory });
return;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"dev": "docusaurus start",
"build-carlin": "yarn workspace carlin build",
"prebuild": "yarn run build-carlin",
"build": "docusaurus build",
"build": "echo docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "carlin deploy static-app",
"deploy": "echo carlin deploy static-app",
"serve": "docusaurus serve",
"clear": "docusaurus clear"
},
Expand Down
Loading

0 comments on commit 92de986

Please sign in to comment.