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

[INTEG-1417] Update aiig create upload function to handle latest upload function for both spaceId and environmentId #5324

Merged
merged 7 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,069 changes: 1,058 additions & 11 deletions apps/ai-image-generator/backend/package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion apps/ai-image-generator/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"dependencies": {
"@contentful/node-apps-toolkit": "^2.6.0",
"contentful-management": "^10.46.4",
"contentful-management": "^11.6.1",
"openai": "^4.20.1",
"sharp": "^0.33.0"
},
Expand All @@ -26,6 +26,8 @@
"@types/sinon-chai": "^3.2.9",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"node-addon-api": "^7.0.0",
"node-gyp": "^10.0.1",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two are required by sharp 0.33 for our installation to work locally

"sinon": "^15.2.0",
"sinon-chai": "^3.7.0",
"ts-node": "^10.9.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { AppActionCallContext } from '@contentful/node-apps-toolkit';
import { PlainClientAPI } from 'contentful-management';
import { OpenAiApiService } from '../services/openaiApiService';
import { AppActionCallResponse, Image } from '../types';
import { fetchOpenAiApiKey } from '../utils';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ describe('aiigSelectEdit.handler', () => {
sys: {
type: 'Link',
linkType: 'Space',
id: 'spaceId',
id: 'space-id',
},
},
environment: {
sys: {
type: 'Link',
linkType: 'Environment',
id: 'environment-id',
},
},
expiresAt: '2015-05-18T11:29:46.809Z',
Expand Down Expand Up @@ -114,7 +121,7 @@ describe('aiigSelectEdit.handler', () => {
// using match here to just match the beginning because there's a small race condition in tests where
// sometimes the first image result gets assigned a different upload id
expect(result.data.images[0].upload.url).to.match(
/^https:\/\/s3\.us-east-1\.amazonaws\.com\/upload-api\.contentful\.com\/space-id!upload!uploadId/
/^https:\/\/s3\.us-east-1\.amazonaws\.com\/upload-api\.contentful\.com\/space-id!environment-id!upload!uploadId/
);
expect(result.data.images[0].upload.sys.id).to.match(/^uploadId/);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const handler = async (
): Promise<AppActionCallResponse<ImageEditResult>> => {
const {
cma,
appActionCallContext: { appInstallationId, spaceId, uploadHost },
appActionCallContext: { appInstallationId, spaceId, environmentId, uploadHost },
} = context;

let images: ImageWithUpload[];
Expand Down Expand Up @@ -72,6 +72,7 @@ export const handler = async (
imagesWithStreams: processedImages,
cmaClient: cma,
spaceId,
environmentId,
uploadHost,
});
} catch (e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import { expect } from 'chai';
describe('UploadImages', () => {
let uploadImages: UploadImages;
const spaceId = 'spaceId';
const environmentId = 'environmentId';
const uploadId = 'uploadId';
const sourceUrl = 'http://www.example.com';
const uploadHost = 'upload.contentful.com';
const cmaClientStub = sinon.stub();

describe('execute', () => {
afterEach(() => {
cmaClientStub.reset();
});

beforeEach(async () => {
const imagePath = absolutePathToFile('./test/mocks/images/peaceful-cat.jpg');
const imageResponse = await responseFromFile(imagePath);
Expand All @@ -31,6 +36,13 @@ describe('UploadImages', () => {
id: spaceId,
},
},
environment: {
sys: {
type: 'Link',
linkType: 'Environment',
id: environmentId,
},
},
expiresAt: '2015-05-18T11:29:46.809Z',
createdAt: '2015-05-18T11:29:46.809Z',
createdBy: {
Expand All @@ -44,7 +56,13 @@ describe('UploadImages', () => {
};

const cmaClient = makeMockPlainClient([mockUploadApiResponse], cmaClientStub);
uploadImages = new UploadImages(imagesWithStreams, cmaClient, spaceId, uploadHost);
uploadImages = new UploadImages(
imagesWithStreams,
cmaClient,
spaceId,
environmentId,
uploadHost
);
});

it('returns images with correct urls', async () => {
Expand All @@ -56,8 +74,58 @@ describe('UploadImages', () => {
expect(relativeImageSizeDiff).to.below(0.1);
expect(image.upload).to.have.property(
'url',
`https://s3.us-east-1.amazonaws.com/upload-api.contentful.com/${spaceId}!upload!${uploadId}`
`https://s3.us-east-1.amazonaws.com/upload-api.contentful.com/${spaceId}!${environmentId}!upload!${uploadId}`
);
});

describe('when environment id not present in upload response', () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep an explicit test that ensures correct behavior if for some reason the old upload (without environment id) is created.

beforeEach(async () => {
const imagePath = absolutePathToFile('./test/mocks/images/peaceful-cat.jpg');
const imageResponse = await responseFromFile(imagePath);
const imagesWithStreams = [
{ url: sourceUrl, imageType: 'png', stream: toSharp(imageResponse.body) },
];
const mockUploadApiResponse = {
sys: {
type: 'Upload',
id: uploadId,
space: {
sys: {
type: 'Link',
linkType: 'Space',
id: spaceId,
},
},
expiresAt: '2015-05-18T11:29:46.809Z',
createdAt: '2015-05-18T11:29:46.809Z',
createdBy: {
sys: {
type: 'Link',
linkType: 'User',
id: '4FLrUHftHW3v2BLi9fzfjU',
},
},
},
};

const cmaClient = makeMockPlainClient([mockUploadApiResponse], cmaClientStub);
uploadImages = new UploadImages(
imagesWithStreams,
cmaClient,
spaceId,
environmentId,
uploadHost
);
});

it('returns images without environment id in urls', async () => {
const result = await uploadImages.execute();
const image = result[0];
expect(image.upload).to.have.property(
'url',
`https://s3.us-east-1.amazonaws.com/upload-api.contentful.com/${spaceId}!upload!${uploadId}`
);
});
});
});
});
39 changes: 30 additions & 9 deletions apps/ai-image-generator/backend/src/helpers/upload-images.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PlainClientAPI, UploadProps } from 'contentful-management';
import { SysLink, UploadProps } from 'contentful-management';
import { AppActionCallContext } from '@contentful/node-apps-toolkit';
import { ImageWithStream, ImageWithUpload } from '../types';
import sharp from 'sharp';
import { toDimensions } from '../utils';
Expand All @@ -10,11 +11,17 @@ const UPLOAD_DOMAIN: Record<string, URL> = {
),
};

type UploadPropsWithEnvironment = {
// TODO: use upstream UplpadProps directly once environment id has been added
sys: UploadProps['sys'] & { environment?: SysLink };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: typo in this comment, UplpadPropsshould be UploadProps 😄

};

export class UploadImages {
constructor(
readonly imagesWithStreams: ImageWithStream[],
readonly cmaClient: PlainClientAPI,
readonly cmaClient: AppActionCallContext['cma'],
readonly spaceId: string,
readonly environmentId: string,
readonly uploadHost: string
) {}

Expand Down Expand Up @@ -52,13 +59,20 @@ export class UploadImages {
return { dimensions, size };
}

private async createUpload(file: sharp.Sharp): Promise<UploadProps> {
return await this.cmaClient.upload.create({ spaceId: this.spaceId }, { file });
private async createUpload(file: sharp.Sharp): Promise<UploadPropsWithEnvironment> {
return await this.cmaClient.upload.create(
{ spaceId: this.spaceId, environmentId: this.environmentId },
{ file }
);
}

private urlFromUpload(upload: UploadProps): string {
private urlFromUpload(upload: UploadPropsWithEnvironment): string {
const uploadId = upload.sys.id;
const uploadPath = `${this.spaceId}!upload!${uploadId}`;
const spaceId = upload.sys.space.sys.id;
const environmentId = upload.sys.environment && upload.sys.environment.sys.id;
const uploadPath = environmentId
? `${spaceId}!${environmentId}!upload!${uploadId}`
: `${spaceId}!upload!${uploadId}`;
const uploadDomain = UPLOAD_DOMAIN[this.uploadHost];
if (!uploadDomain)
throw new Error(`Invalid uploadHost '${this.uploadHost}' -- could not find upload bucket`);
Expand All @@ -68,11 +82,18 @@ export class UploadImages {

export const uploadImages = async (params: {
imagesWithStreams: ImageWithStream[];
cmaClient: PlainClientAPI;
cmaClient: AppActionCallContext['cma'];
spaceId: string;
environmentId: string;
uploadHost: string;
}) => {
const { imagesWithStreams, cmaClient, spaceId, uploadHost } = params;
const imageUploader = new UploadImages(imagesWithStreams, cmaClient, spaceId, uploadHost);
const { imagesWithStreams, cmaClient, spaceId, environmentId, uploadHost } = params;
const imageUploader = new UploadImages(
imagesWithStreams,
cmaClient,
spaceId,
environmentId,
uploadHost
);
return imageUploader.execute();
};
4 changes: 2 additions & 2 deletions apps/ai-image-generator/backend/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PlainClientAPI } from 'contentful-management';
import { AppActionCallContext } from '@contentful/node-apps-toolkit';
import { default as sharp } from 'sharp';
import { Dimensions } from './types';

Expand All @@ -8,7 +8,7 @@ export interface AreEqualColorOpts {
}

export async function fetchOpenAiApiKey(
cma: PlainClientAPI,
cma: AppActionCallContext['cma'],
appInstallationId: string
): Promise<string> {
const appInstallation = await cma.appInstallation.get({ appDefinitionId: appInstallationId });
Expand Down
Loading
Loading