Skip to content

Commit

Permalink
fix(results): 🐛 Remove storage on result delete
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Jun 26, 2022
1 parent fc4db57 commit 56dca86
Show file tree
Hide file tree
Showing 5 changed files with 2,408 additions and 2,808 deletions.
2 changes: 2 additions & 0 deletions apps/builder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"kbar": "^0.1.0-beta.34",
"micro": "^9.3.4",
"micro-cors": "^0.1.1",
"minio": "^7.0.28",
"models": "*",
"next": "^12.1.6",
"next-auth": "4.3.4",
Expand Down Expand Up @@ -91,6 +92,7 @@
"@types/google-spreadsheet": "^3.2.1",
"@types/jsonwebtoken": "8.5.8",
"@types/micro-cors": "^0.1.2",
"@types/minio": "^7.0.13",
"@types/node": "^17.0.33",
"@types/nodemailer": "^6.4.4",
"@types/nprogress": "^0.2.0",
Expand Down
37 changes: 18 additions & 19 deletions apps/builder/pages/api/typebots/[typebotId]/results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,25 +55,24 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
id: ids.length > 0 ? { in: ids } : undefined,
typebot: canWriteTypebot(typebotId, user),
}
// Weird bug waiting for https://github.com/aws/aws-sdk-js/issues/4137
// const typebot = await prisma.typebot.findFirst({
// where: canWriteTypebot(typebotId, user),
// select: { groups: true },
// })
// if (!typebot) return forbidden(res)
// const fileUploadBlockIds = (typebot as Typebot).groups
// .flatMap((g) => g.blocks)
// .filter((b) => b.type === InputBlockType.FILE)
// .map((b) => b.id)
// if (fileUploadBlockIds.length > 0) {
// const filesToDelete = await prisma.answer.findMany({
// where: { result: resultsFilter, blockId: { in: fileUploadBlockIds } },
// })
// if (filesToDelete.length > 0)
// await deleteFiles({
// urls: filesToDelete.flatMap((a) => a.content.split(', ')),
// })
// }
const typebot = await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
select: { groups: true },
})
if (!typebot) return forbidden(res)
const fileUploadBlockIds = (typebot as Typebot).groups
.flatMap((g) => g.blocks)
.filter((b) => b.type === InputBlockType.FILE)
.map((b) => b.id)
if (fileUploadBlockIds.length > 0) {
const filesToDelete = await prisma.answer.findMany({
where: { result: resultsFilter, blockId: { in: fileUploadBlockIds } },
})
if (filesToDelete.length > 0)
await deleteFiles({
urls: filesToDelete.flatMap((a) => a.content.split(', ')),
})
}
await prisma.log.deleteMany({
where: {
result: resultsFilter,
Expand Down
42 changes: 17 additions & 25 deletions apps/builder/services/api/storage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { AWSError, config, Endpoint, S3 } from 'aws-sdk'
import { PromiseResult } from 'aws-sdk/lib/request'
import { Client } from 'minio'

export const deleteFiles = async ({
urls,
}: {
urls: string[]
}): Promise<PromiseResult<S3.DeleteObjectsOutput, AWSError>> => {
}): Promise<void> => {
if (
!process.env.S3_ENDPOINT ||
!process.env.S3_ACCESS_KEY ||
Expand All @@ -15,30 +14,23 @@ export const deleteFiles = async ({
'S3 not properly configured. Missing one of those variables: S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEY'
)

const sslEnabled =
const useSSL =
process.env.S3_SSL && process.env.S3_SSL === 'false' ? false : true
config.update({
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_KEY,
const minioClient = new Client({
endPoint: process.env.S3_ENDPOINT,
port: process.env.S3_PORT ? parseInt(process.env.S3_PORT) : undefined,
useSSL,
accessKey: process.env.S3_ACCESS_KEY,
secretKey: process.env.S3_SECRET_KEY,
region: process.env.S3_REGION,
sslEnabled,
})
const protocol = sslEnabled ? 'https' : 'http'
const s3 = new S3({
endpoint: new Endpoint(
`${protocol}://${process.env.S3_ENDPOINT}${
process.env.S3_PORT ? `:${process.env.S3_PORT}` : ''
}`
),
})

const Bucket = process.env.S3_BUCKET ?? 'typebot'
return s3
.deleteObjects({
Bucket,
Delete: {
Objects: urls.map((url) => ({ Key: url.split(`/${Bucket}/`)[1] })),
},
})
.promise()
const bucket = process.env.S3_BUCKET ?? 'typebot'

return minioClient.removeObjects(
bucket,
urls
.filter((url) => url.includes(process.env.S3_ENDPOINT as string))
.map((url) => url.split(`/${bucket}/`)[1])
)
}
48 changes: 29 additions & 19 deletions apps/viewer/playwright/tests/fileUpload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { parse } from 'papaparse'
import { typebotViewer } from '../services/selectorUtils'
import { importTypebotInDatabase } from '../services/database'
import { readFileSync } from 'fs'
import { isDefined } from 'utils'

test('should work as expected', async ({ page }) => {
test('should work as expected', async ({ page, browser }) => {
const typebotId = cuid()
await importTypebotInDatabase(
path.join(__dirname, '../fixtures/typebots/fileUpload.json'),
Expand Down Expand Up @@ -51,24 +52,33 @@ test('should work as expected', async ({ page }) => {
expect(data).toHaveLength(2)
expect((data[1] as unknown[])[1]).toContain('http://localhost:9000')

// Waiting for https://github.com/aws/aws-sdk-js/issues/4137
// const urls = (
// await Promise.all(
// [
// page.locator('text="api.json"'),
// page.locator('text="fileUpload.json"'),
// page.locator('text="hugeGroup.json"'),
// ].map((elem) => elem.getAttribute('href'))
// )
// ).filter(isDefined)
const urls = (
await Promise.all(
[
page.locator('text="api.json"'),
page.locator('text="fileUpload.json"'),
page.locator('text="hugeGroup.json"'),
].map((elem) => elem.getAttribute('href'))
)
).filter(isDefined)

// const page2 = await browser.newPage()
// await page2.goto(urls[0])
// await expect(page2.locator('pre')).toBeVisible()
const page2 = await browser.newPage()
await page2.goto(urls[0])
await expect(page2.locator('pre')).toBeVisible()

// await page.locator('button >> text="Delete"').click()
// await page.locator('button >> text="Delete" >> nth=1').click()
// await expect(page.locator('text="api.json"')).toBeHidden()
// await page2.goto(urls[0])
// await expect(page2.locator('text="grkwobnowrk')).toBeVisible()
await page.locator('button >> text="Delete"').click()
await page.locator('button >> text="Delete" >> nth=1').click()
await expect(page.locator('text="api.json"')).toBeHidden()
await page2.goto(urls[0])
await expect(
page2.locator('span:has-text("The specified key does not exist.")')
).toBeVisible()
await page2.goto(urls[1])
await expect(
page2.locator('span:has-text("The specified key does not exist.")')
).toBeVisible()
await page2.goto(urls[2])
await expect(
page2.locator('span:has-text("The specified key does not exist.")')
).toBeVisible()
})
Loading

2 comments on commit 56dca86

@vercel
Copy link

@vercel vercel bot commented on 56dca86 Jun 26, 2022

Choose a reason for hiding this comment

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

@vercel
Copy link

@vercel vercel bot commented on 56dca86 Jun 26, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

viewer-v2-alpha – ./apps/viewer

bt.id8rs.com
apo.nigerias.io
apr.nigerias.io
sat.cr8.ai
ar.nigerias.io
vhpage.cr8.ai
am.nigerias.io
an.nigerias.io
bot.aws.bj
aso.nigerias.io
eventhub.com.au
bot.upfunnel.art
chat.sureb4.com
bot.piccinato.co
games.klujo.com
sakuranembro.it
clo.closeer.work
stan.vselise.com
faqs.nigerias.io
feedback.ofx.one
app.chatforms.net
voicehelp.cr8.ai
this-is-a-test.com
ov3.wpwakanda.com
ov1.wpwakanda.com
gentleman-shop.fr
ov2.wpwakanda.com
goalsettingbot.com
zap.techadviser.in
bot.eventhub.com.au
forms.webisharp.com
bot.ansuraniphone.my
typebot.stillio.com
bot.cotemeuplano.com
get.freebotoffer.xyz
chat.hayurihijab.com
bbutton.wpwakanda.com
abutton.wpwakanda.com
bot.incusservices.com
bot.meuesocial.com.br
sbutton.wpwakanda.com
chat.missarkansas.org
bbutton.wpwwakanda.com
cdd.searchcube.com.sg
apply.ansuraniphone.my
felipewelington.com.br
c23111azqw.nigerias.io
form.searchcube.com.sg
gcase.barrettamario.it
info.clickasuransi.com
view.onlinebotdemo.xyz
83242573.actualizar.xyz
subfooter.wpwakanda.com
kodawariab736.skeep.it
mainmenu.diddancing.com
91181264.your-access.one
type.opaulovieira.com.br
form.sergiolimajr.com.br
hunterbot.saleshunter.ai
aibot.angrybranding.co.uk
boyfriend-breakup.riku.ai
bot.cabinrentalagency.com
onboarding.libertydreamcare.ie
type.dericsoncalari.com.br
designguide.techyscouts.com
piazzatorre.barrettamario.it
type.talitasouzamarques.com.br
agendamento.sergiolimajr.com.br
bookings.littlepartymonkeys.com
bot.comercializadoraomicron.com
preagendamento.sergiolimajr.com.br
viewer-v2-alpha-typebot-io.vercel.app
personal-trainer.barrettamario.it
viewer-v2-alpha-git-main-typebot-io.vercel.app
studiotecnicoimmobiliaremerelli.it

Please sign in to comment.