Skip to content

Commit

Permalink
fix: make sure to delete lock on crash
Browse files Browse the repository at this point in the history
  • Loading branch information
mbret committed Mar 17, 2024
1 parent 8170575 commit 1984865
Showing 1 changed file with 83 additions and 79 deletions.
162 changes: 83 additions & 79 deletions packages/api/src/functions/refreshMetadataLongProcess/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,104 +17,108 @@ import { Logger } from "@libs/logger"
const lambda: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (
event
) => {
configureGoogleDataSource({
client_id:
(await getParameterValue({
Name: `GOOGLE_CLIENT_ID`,
WithDecryption: true
})) ?? ``,
client_secret:
(await getParameterValue({
Name: `GOOGLE_CLIENT_SECRET`,
WithDecryption: true
})) ?? ``
})

const googleApiKey = await getParameterValue({
Name: `GOOGLE_API_KEY`,
WithDecryption: true
})

if (!OFFLINE) {
const files = await fs.promises.readdir(TMP_DIR)

await Promise.all(
files.map((file) => {
return fs.promises.unlink(path.join(TMP_DIR, file))
})
)
}

const lockId = `metadata_${event.body.bookId}`
const authorization = event.body.authorization ?? ``
const rawCredentials = event.body.credentials ?? JSON.stringify({})
const credentials = JSON.parse(rawCredentials)

const { name: userName } = await withToken({
headers: {
authorization
try {
configureGoogleDataSource({
client_id:
(await getParameterValue({
Name: `GOOGLE_CLIENT_ID`,
WithDecryption: true
})) ?? ``,
client_secret:
(await getParameterValue({
Name: `GOOGLE_CLIENT_SECRET`,
WithDecryption: true
})) ?? ``
})

const googleApiKey = await getParameterValue({
Name: `GOOGLE_API_KEY`,
WithDecryption: true
})

if (!OFFLINE) {
const files = await fs.promises.readdir(TMP_DIR)

await Promise.all(
files.map((file) => {
return fs.promises.unlink(path.join(TMP_DIR, file))
})
)
}
})
const userNameHex = Buffer.from(userName).toString("hex")
const bookId: string | undefined = event.body.bookId

if (!bookId) {
throw new Error(`Unable to parse event.body -> ${event.body}`)
}
const credentials = JSON.parse(rawCredentials)

const lockId = `metadata_${event.body.bookId}`
const { name: userName } = await withToken({
headers: {
authorization
}
})
const userNameHex = Buffer.from(userName).toString("hex")
const bookId: string | undefined = event.body.bookId

const db = await getNanoDbForUser(userName)
if (!bookId) {
throw new Error(`Unable to parse event.body -> ${event.body}`)
}

const book = await findOne(db, "book", { selector: { _id: bookId } })
const db = await getNanoDbForUser(userName)

if (!book) throw new Error(`Unable to find book ${bookId}`)
const book = await findOne(db, "book", { selector: { _id: bookId } })

if (book.metadataUpdateStatus !== "fetching") {
await atomicUpdate(db, "book", book._id, (old) => ({
...old,
metadataUpdateStatus: "fetching" as const
}))
}
if (!book) throw new Error(`Unable to find book ${bookId}`)

const firstLinkId = (book.links || [])[0] || "-1"
if (book.metadataUpdateStatus !== "fetching") {
await atomicUpdate(db, "book", book._id, (old) => ({
...old,
metadataUpdateStatus: "fetching" as const
}))
}

const link = await findOne(db, "link", { selector: { _id: firstLinkId } })
const firstLinkId = (book.links || [])[0] || "-1"

if (!link) throw new Error(`Unable to find link ${firstLinkId}`)
const link = await findOne(db, "link", { selector: { _id: firstLinkId } })

let data: PromiseReturnType<typeof retrieveMetadataAndSaveCover>
if (!link) throw new Error(`Unable to find link ${firstLinkId}`)

try {
data = await retrieveMetadataAndSaveCover({
userName,
userNameHex,
credentials,
book,
link,
googleApiKey,
db
})
} catch (e) {
await atomicUpdate(db, "book", book._id, (old) => ({
...old,
metadataUpdateStatus: null,
lastMetadataUpdateError: "unknown"
}))
let data: PromiseReturnType<typeof retrieveMetadataAndSaveCover>

await deleteLock(supabase, lockId)
try {
data = await retrieveMetadataAndSaveCover({
userName,
userNameHex,
credentials,
book,
link,
googleApiKey,
db
})
} catch (e) {
await atomicUpdate(db, "book", book._id, (old) => ({
...old,
metadataUpdateStatus: null,
lastMetadataUpdateError: "unknown"
}))

throw e
}

throw e
}
await Promise.all([
atomicUpdate(db, "link", link._id, (old) => ({
...old,
contentLength: data.link.contentLength
})),
deleteLock(supabase, lockId)
])

await Promise.all([
atomicUpdate(db, "link", link._id, (old) => ({
...old,
contentLength: data.link.contentLength
})),
deleteLock(supabase, lockId)
])
Logger.info(`lambda executed with success for ${book._id}`)
} catch (error) {
await deleteLock(supabase, lockId)

Logger.info(`lambda executed with success for ${book._id}`)
throw error
}

return {
statusCode: 200,
Expand Down

0 comments on commit 1984865

Please sign in to comment.