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

Add schedule action with support for once and now schedule periods #7

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
17 changes: 8 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,33 @@
"postinstall": "yarn prisma generate"
},
"dependencies": {
"handlebars": "^4.7.7",
"express": "^4.18.2",
"@aws-sdk/client-s3": "^3.109.0",
"@aws-sdk/s3-request-presigner": "^3.109.0",
"@interval/sdk": "2.0.0",
"@prisma/client": "^5.3.0",
"prisma": "^5.3.0",
"@prisma/generator-helper": "^5.3.0",
"@trpc/client": "^9.16.0",
"@trpc/react": "^9.16.0",
"@trpc/server": "^9.16.0",
"@workos-inc/node": "^2.20.0",
"commander": "^11.1.0",
"croner": "^8.0.0",
"cross-fetch": "^3.1.5",
"devalue": "^2.0.1",
"dotenv": "^16.3.1",
"ee-ts": "^1.0.2",
"email-templates": "^8.0.8",
"evt": "^2.4.10",
"express": "^4.18.2",
"generate-password": "^1.7.0",
"glob": "^8.0.3",
"handlebars": "^4.7.7",
"iron-session": "^6.0.5",
"loglevel": "^1.8.1",
"luxon": "^3.0.4",
"node-cron": "^3.0.1",
"postmark": "^3.0.14",
"preview-email": "^3.0.6",
"prisma": "^5.3.0",
"request-ip": "^3.3.0",
"sanitize-html": "^2.11.0",
"superjson": "^1.7.4",
Expand All @@ -79,8 +80,7 @@
"uuid": "^9.0.0",
"winston": "^3.8.2",
"ws": "^8.4.1",
"zod": "^3.13.3",
"dotenv": "^16.3.1"
"zod": "^3.13.3"
},
"devDependencies": {
"@babel/core": "^7.16.7",
Expand Down Expand Up @@ -124,7 +124,6 @@
"@types/luxon": "^3.0.2",
"@types/mdx": "^2.0.1",
"@types/node": "^17.0.18",
"@types/node-cron": "^3.0.1",
"@types/papaparse": "^5.3.1",
"@types/preview-email": "^3.0.1",
"@types/react": "^18.0.23",
Expand Down Expand Up @@ -175,6 +174,7 @@
"react-loading-skeleton": "^3.1.0",
"react-markdown": "^8.0.0",
"react-query": "^3.27.0",
"react-router-dom": "6.3.x",
"react-scroll-sync": "^0.11.0",
"react-select": "^5.2.2",
"react-transition-group": "^4.4.2",
Expand All @@ -196,8 +196,7 @@
"vite": "^3.2.0",
"vite-plugin-checker": "^0.6.2",
"vite-tsconfig-paths": "^4.0.5",
"xlsx": "^0.18.5",
"react-router-dom": "6.3.x"
"xlsx": "^0.18.5"
},
"resolutions": {
"ts-node": "^10.9.1"
Expand Down
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -536,13 +536,15 @@ model ActionSchedule {
id String @id @default(dbgenerated("nanoid()"))
actionId String
runnerId String?
once Boolean @default(false)

second String
minute String
hour String
dayOfMonth String
month String
dayOfWeek String
date String?
timeZoneName String

notifyOnSuccess Boolean @default(false)
Expand Down
21 changes: 15 additions & 6 deletions src/components/ActionSettings/Schedule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ function ActionSchedule({
className="md:w-[140px]"
onChange={e =>
updateInput({
schedulePeriod: e.target.value as SchedulePeriod,
schedulePeriod: e.target.value as Exclude<
SchedulePeriod,
'once' | 'now'
>,
})
}
value={input.schedulePeriod}
Expand Down Expand Up @@ -367,11 +370,17 @@ export default function ActionScheduleSettings({

const actionScheduleInputs = useMemo(
() =>
action.schedules.map(s => ({
id: s.id,
runnerName: s.runner ? displayName(s.runner) : undefined,
...toScheduleInput(s),
})),
action.schedules.flatMap(s => {
const input = {
id: s.id,
runnerName: s.runner ? displayName(s.runner) : undefined,
...toScheduleInput(s),
}
if (input.schedulePeriod === 'once' || input.schedulePeriod === 'now') {
return []
}
return [input]
}),
[action.schedules]
)

Expand Down
97 changes: 97 additions & 0 deletions src/server/api/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,36 @@ import prisma from '../prisma'
import { loginWithApiKey } from '../auth'
import { getQueuedActionParams } from '~/utils/queuedActions'
import { logger } from '~/server/utils/logger'
import { ALL_TIMEZONES } from '~/utils/timezones'
import { syncActionSchedules } from '../utils/actionSchedule'

const router = express.Router()

const SCHEDULE_ACTION = {
inputs: z.object({
slug: z.string(),
schedulePeriod: z.enum(['now', 'once', 'hour', 'day', 'week', 'month']),
timeZoneName: z.enum(ALL_TIMEZONES).optional(),
seconds: z.number().optional(),
hours: z.number().optional(),
minutes: z.number().optional(),
dayOfWeek: z.number().optional(),
dayOfMonth: z.number().optional(),
date: z.string().optional().nullable(),
runnerId: z.string().optional().nullable(),
notifyOnSuccess: z.boolean().optional(),
}),
returns: z.discriminatedUnion('type', [
z.object({
type: z.literal('success'),
}),
z.object({
type: z.literal('error'),
message: z.string(),
}),
]),
}

router.post('/enqueue', async (req, res) => {
// To ensure correct return type
function sendResponse(
Expand Down Expand Up @@ -194,4 +221,74 @@ router.post('/dequeue', async (req, res) => {
})
})

router.post('/schedule', async (req, res) => {
// To ensure correct return type
function sendResponse(
statusCode: number,
returns: z.input<(typeof SCHEDULE_ACTION)['returns']>
) {
res.status(statusCode).send(returns)
}

const apiKey = req.headers.authorization?.split(' ')[1]

if (!apiKey) {
return sendResponse(401, {
type: 'error',
message: 'No API key provided.',
})
}

const auth = await loginWithApiKey(apiKey)

if (!auth) {
return sendResponse(403, {
type: 'error',
message: 'Invalid API key provided.',
})
}

let inputs: z.infer<(typeof SCHEDULE_ACTION)['inputs']>
try {
inputs = SCHEDULE_ACTION.inputs.parse(req.body)
} catch (err) {
return sendResponse(400, {
type: 'error',
message: JSON.stringify(err),
})
}

const { slug: actionSlug, ...scheduleInput } = inputs

const action = await prisma.action.findFirst({
where: {
slug: inputs.slug,
organizationId: auth.organization.id,
developerId:
auth.apiKey.usageEnvironment === 'DEVELOPMENT' ? auth.user.id : null,
organizationEnvironmentId: auth.apiKey.organizationEnvironmentId,
},
include: {
schedules: {
where: {
deletedAt: null,
},
},
},
})

if (!action) {
return sendResponse(404, {
type: 'error',
message: 'Action not found.',
})
}

await syncActionSchedules(action, [scheduleInput])

sendResponse(200, {
type: 'success',
})
})

export default router
3 changes: 2 additions & 1 deletion src/server/trpc/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,12 +587,13 @@ export const actionRouter = createRouter()
actionScheduleInputs: z.array(
z.object({
id: z.string().optional(), // Used on frontend only, here for types
schedulePeriod: z.enum(['hour', 'day', 'week', 'month']),
schedulePeriod: z.enum(['now', 'once', 'hour', 'day', 'week', 'month']),
timeZoneName: z.enum(ALL_TIMEZONES).optional(),
hours: z.number().int().optional(),
minutes: z.number().int().optional(),
dayOfWeek: z.number().int().optional(),
dayOfMonth: z.number().int().optional(),
date: z.string().nullish(),
notifyOnSuccess: z.boolean().optional(),
runnerId: z.string().nullish(),
})
Expand Down
12 changes: 8 additions & 4 deletions src/server/utils/actionSchedule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as cron from 'node-cron'
import { Cron } from 'croner'
import { ActionSchedule } from '@prisma/client'
import {
CronSchedule,
Expand All @@ -12,12 +12,16 @@ import { makeApiCall } from './wss'
export function isInputValid(input: ScheduleInput): boolean {
const schedule = toCronSchedule(input)
if (!schedule) return false

return cron.validate(cronScheduleToString(schedule))
return isValid(schedule)
}

export function isValid(schedule: CronSchedule): boolean {
return cron.validate(cronScheduleToString(schedule))
try {
Cron(cronScheduleToString(schedule), { maxRuns: 0 })
return true
} catch {
return false
}
}

export async function syncActionSchedules(
Expand Down
Loading