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

refactor(pg-v5): Move command pg:backups:unschedule to oclif #2749

Merged
merged 5 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
55 changes: 55 additions & 0 deletions packages/cli/src/commands/pg/backups/unschedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import color from '@heroku-cli/color'
import {Command, flags} from '@heroku-cli/command'
import {Args, ux} from '@oclif/core'
import {arbitraryAppDB, getAddon} from '../../../lib/pg/fetcher'
import {TransferSchedule} from '../../../lib/pg/types'
import pgHost from '../../../lib/pg/host'

export default class Unschedule extends Command {
static topic = 'pg';
static description = 'stop daily backups';
static flags = {
app: flags.app({required: true}),
};

static args = {
database: Args.string(),
};

public async run(): Promise<void> {
const {flags, args} = await this.parse(Unschedule)
const {app} = flags
const {database} = args
let db = database
if (!db) {
const appDB = await arbitraryAppDB(this.heroku, app)
const {body: schedules} = await this.heroku.get<TransferSchedule[]>(
`/client/v11/databases/${appDB.id}/transfer-schedules`,
{hostname: pgHost()},
)
if (schedules.length === 0)
throw new Error(`No schedules on ${color.app(app)}`)
if (schedules.length > 1) {
throw new Error(`Specify schedule on ${color.app(app)}. Existing schedules: ${schedules.map(s => color.green(s.name))
.join(', ')}`)
}

db = schedules[0].name
}

ux.action.start(`Unscheduling ${color.green(db)} daily backups`)
const addon = await getAddon(this.heroku, app, db)
const {body: schedules} = await this.heroku.get<TransferSchedule[]>(
`/client/v11/databases/${addon.id}/transfer-schedules`,
{hostname: pgHost()},
)
const schedule = schedules.find(s => s.name.match(new RegExp(`${db}`, 'i')))
if (!schedule)
throw new Error(`No daily backups found for ${color.yellow(addon.name)}`)
await this.heroku.delete(
`/client/v11/databases/${addon.id}/transfer-schedules/${schedule.uuid}`,
{hostname: pgHost()},
)
ux.action.stop()
}
}
6 changes: 5 additions & 1 deletion packages/cli/src/lib/pg/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function arbitraryAppDB(heroku: APIClient, app: string) {

pgDebug(`fetching arbitrary app db on ${app}`)
const {body: addons} = await heroku.get<Heroku.AddOn[]>(`/apps/${app}/addons`)
const addon = addons.find(a => a.app?.name === app && a.plan?.name?.startsWith('heroku-postgresql'))
const addon = addons.find(a => a?.app?.name === app && a?.plan?.name?.startsWith('heroku-postgresql'))
if (!addon) throw new Error(`No heroku-postgresql databases on ${app}`)
return addon
}
Expand Down Expand Up @@ -103,3 +103,7 @@ async function allAttachments(heroku: APIClient, app: string) {
})
return attachments.filter((a: AddOnAttachmentWithConfigVarsAndPlan) => a.addon.plan?.name?.startsWith('heroku-postgresql'))
}

export async function getAddon(heroku: APIClient, app: string, db: string) {
return ((await attachment(heroku, app, db))).addon
}
1 change: 1 addition & 0 deletions packages/cli/src/lib/pg/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type TransferSchedule = {
hour: number,
name: string,
timezone: string,
uuid: string,
}
export type AddOnWithPlan = Required<Heroku.AddOnAttachment['addon']> & {plan: Heroku.AddOn['plan']}
export type AddOnAttachmentWithConfigVarsAndPlan = Heroku.AddOnAttachment & {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import {stderr, stdout} from 'stdout-stderr'
import Cmd from '../../../../../src/commands/pg/backups/unschedule'
import runCommand from '../../../../helpers/runCommand'
import * as nock from 'nock'
import heredoc from 'tsheredoc'
import {expect} from 'chai'
import expectOutput from '../../../../helpers/utils/expectOutput'
import * as fixtures from '../../../../fixtures/addons/fixtures'
import stripAnsi = require('strip-ansi')

const shouldUnschedule = function (cmdRun: (args: string[]) => Promise<any>) {
const addon = fixtures.addons['www-db']
const attachment = {addon}
const appName = addon.app?.name || 'myapp'

beforeEach(() => {
nock('https://api.heroku.com')
.get(`/apps/${appName}/addons`)
.reply(200, [addon])
.post('/actions/addon-attachments/resolve', {
app: appName,
addon_attachment: 'DATABASE_URL',
addon_service: 'heroku-postgresql',
})
.reply(200, [attachment])
nock('https://api.data.heroku.com')
.get(`/client/v11/databases/${addon.id}/transfer-schedules`)
.twice()
.reply(200, [{name: 'DATABASE_URL', uuid: '100-001'}])
.delete(`/client/v11/databases/${addon.id}/transfer-schedules/100-001`)
.reply(200)
})
afterEach(() => {
nock.cleanAll()
})

it('unschedules a backup', async () => {
await cmdRun(['--app', appName])
expectOutput(stdout.output, '')
expectOutput(stderr.output, heredoc(`
Unscheduling DATABASE_URL daily backups...
Unscheduling DATABASE_URL daily backups... done
`))
})
}

describe('pg:backups:unschedule', () => {
shouldUnschedule((args: string[]) => runCommand(Cmd, args))
})

describe('pg:backups:unschedule error state', () => {
const addon = fixtures.addons['www-db']
const attachment = {addon}
const appName = addon.app?.name || 'myapp'

beforeEach(() => {
nock('https://api.heroku.com')
.get(`/apps/${appName}/addons`)
.reply(200, [addon])
.post('/actions/addon-attachments/resolve', {
app: appName,
addon_attachment: 'DATABASE_URL',
addon_service: 'heroku-postgresql',
})
.reply(200, [attachment])
nock('https://api.data.heroku.com')
.get(`/client/v11/databases/${addon.id}/transfer-schedules`)
.twice()
.reply(200, [
{
name: 'DATABASE_URL',
uuid: '100-001',
},
{
name: 'DATABASE_URL2',
uuid: '100-002',
},
])
})
afterEach(() => {
nock.cleanAll()
})

it('errors when multiple schedules are returned from API', async () => {
await runCommand(Cmd, ['--app', appName])
.catch(error => expect(stripAnsi(error.message)).to.equal(`Specify schedule on ⬢ ${appName}. Existing schedules: DATABASE_URL, DATABASE_URL2`))
})
})
44 changes: 0 additions & 44 deletions packages/pg-v5/commands/backups/unschedule.js

This file was deleted.

1 change: 0 additions & 1 deletion packages/pg-v5/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ exports.commands = flatten([
require('./commands/backups/cancel'),
require('./commands/backups/capture'),
require('./commands/backups/restore'),
require('./commands/backups/unschedule'),
require('./commands/bloat'),
require('./commands/blocking'),
require('./commands/connection_pooling'),
Expand Down

This file was deleted.

Loading