Skip to content

feat(server): recover the application and synchronize the recovery fu… #1879

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

Merged
merged 2 commits into from
Mar 2, 2024
Merged
Changes from 1 commit
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
114 changes: 106 additions & 8 deletions server/src/database/database.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import { GenerateAlphaNumericPassword } from 'src/utils/random'
import { MongoService } from './mongo.service'
import * as mongodb_uri from 'mongodb-uri'
import { RegionService } from 'src/region/region.service'
import { TASK_LOCK_INIT_TIME } from 'src/constants'
import {
CN_PUBLISHED_CONF,
CN_PUBLISHED_FUNCTIONS,
CN_PUBLISHED_WEBSITE_HOSTING,
TASK_LOCK_INIT_TIME,
} from 'src/constants'
import { Region } from 'src/region/entities/region'
import { SystemDatabase } from '../system-database'
import {
Expand All @@ -18,6 +23,9 @@ import { exec } from 'node:child_process'
import { promisify } from 'node:util'
import { DatabaseSyncRecord } from './entities/database-sync-record'
import { MongoClient, ObjectId } from 'mongodb'
import { DedicatedDatabaseService } from './dedicated-database/dedicated-database.service'
import { CloudFunction } from 'src/function/entities/cloud-function'
import { ApplicationConfiguration } from 'src/application/entities/application-configuration'

const p_exec = promisify(exec)

Expand All @@ -29,6 +37,7 @@ export class DatabaseService {
constructor(
private readonly mongoService: MongoService,
private readonly regionService: RegionService,
private readonly dedicatedDatabaseService: DedicatedDatabaseService,
) {}

async create(appid: string) {
Expand Down Expand Up @@ -226,10 +235,28 @@ export class DatabaseService {

async exportDatabase(appid: string, filePath: string, uid: ObjectId) {
const region = await this.regionService.findByAppId(appid)
const database = await this.findOne(appid)
assert(database, 'Database not found')
const sharedDatabase = await this.findOne(appid)
const dedicatedDatabase = await this.dedicatedDatabaseService.findOne(appid)

if (sharedDatabase && dedicatedDatabase) {
throw new Error('Database found in both shared and dedicated databases.')
}

if (!sharedDatabase && !dedicatedDatabase) {
throw new Error(
'Database not found in both shared and dedicated databases.',
)
}
let connectionUri
if (sharedDatabase) {
connectionUri = this.getControlConnectionUri(region, sharedDatabase)
} else {
connectionUri = await this.dedicatedDatabaseService.getConnectionUri(
region,
dedicatedDatabase,
)
}

const connectionUri = this.getControlConnectionUri(region, database)
assert(connectionUri, 'Database connection uri not found')

try {
Expand All @@ -252,17 +279,38 @@ export class DatabaseService {
uid: ObjectId,
): Promise<void> {
const region = await this.regionService.findByAppId(appid)
const database = await this.findOne(appid)
assert(database, 'Database not found')

const connectionUri = this.getControlConnectionUri(region, database)
const sharedDatabase = await this.findOne(appid)
const dedicatedDatabase = await this.dedicatedDatabaseService.findOne(appid)

if (sharedDatabase && dedicatedDatabase) {
throw new Error('Database found in both shared and dedicated databases.')
}

if (!sharedDatabase && !dedicatedDatabase) {
throw new Error(
'Database not found in both shared and dedicated databases.',
)
}
let connectionUri
if (sharedDatabase) {
connectionUri = this.getControlConnectionUri(region, sharedDatabase)
} else {
connectionUri = await this.dedicatedDatabaseService.getConnectionUri(
region,
dedicatedDatabase,
)
}
assert(connectionUri, 'Database connection uri not found')

try {
await p_exec(
`mongorestore --uri='${connectionUri}' --gzip --archive='${filePath}' --nsFrom="${dbName}.*" --nsTo="${appid}.*" -v --nsInclude="${dbName}.*"`,
)
await this.db

await this.migrateAppFuncsToSys(appid, uid)

await await this.db
.collection<DatabaseSyncRecord>('DatabaseSyncRecord')
.insertOne({ uid, createdAt: new Date() })
} catch (error) {
Expand All @@ -271,4 +319,54 @@ export class DatabaseService {
throw error
}
}

async migrateAppFuncsToSys(appid: string, uid: ObjectId) {
const { db, client } =
(await this.dedicatedDatabaseService.findAndConnect(appid)) ||
(await this.findAndConnect(appid))

try {
const appFunctionCollection = db.collection(CN_PUBLISHED_FUNCTIONS)
const appConfCollection = db.collection(CN_PUBLISHED_CONF)
const appWebsiteCollection = db.collection(CN_PUBLISHED_WEBSITE_HOSTING)

const functionsExist = await this.db
.collection<CloudFunction>('CloudFunction')
.countDocuments({ appid })

if (functionsExist) {
this.logger.debug('Functions already exist in system database')
return
}

const funcs: CloudFunction[] = await appFunctionCollection
.find<CloudFunction>({})
.toArray()

if (funcs.length === 0) {
this.logger.debug('No functions to migrate.')
return
}

funcs.forEach((func) => {
delete func._id
func.appid = appid
func.createdBy = uid
})

await this.db.collection<CloudFunction>('CloudFunction').insertMany(funcs)

// sync conf
const conf = await this.db
.collection<ApplicationConfiguration>('ApplicationConfiguration')
.findOne({ appid })

await appConfCollection.deleteMany({})
await appConfCollection.insertOne(conf)

await appWebsiteCollection.deleteMany({})
} finally {
await client.close()
}
}
}