Skip to content
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
45 changes: 25 additions & 20 deletions core/actions/_lib/rules.tsx → core/actions/_lib/automations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ import {
} from "lucide-react";
import { z } from "zod";

import type { RulesId } from "db/public";
import type { AutomationsId } from "db/public";
import { Event } from "db/public";
import { CopyButton } from "ui/copy-button";

import { defineRule } from "~/actions/types";
import { defineAutomation } from "~/actions/types";

export const intervals = ["minute", "hour", "day", "week", "month", "year"] as const;
export type Interval = (typeof intervals)[number];

export const pubInStageForDuration = defineRule({
export const pubInStageForDuration = defineAutomation({
event: Event.pubInStageForDuration,
additionalConfig: z.object({
duration: z.number().int().min(1),
Expand All @@ -32,7 +32,7 @@ export const pubInStageForDuration = defineRule({
});
export type PubInStageForDuration = typeof pubInStageForDuration;

export const pubLeftStage = defineRule({
export const pubLeftStage = defineAutomation({
event: Event.pubLeftStage,
display: {
icon: ArrowRightFromLine,
Expand All @@ -41,7 +41,7 @@ export const pubLeftStage = defineRule({
});
export type PubLeftStage = typeof pubLeftStage;

export const pubEnteredStage = defineRule({
export const pubEnteredStage = defineAutomation({
event: Event.pubEnteredStage,
display: {
icon: ArrowRightToLine,
Expand All @@ -50,7 +50,7 @@ export const pubEnteredStage = defineRule({
});
export type PubEnteredStage = typeof pubEnteredStage;

export const actionSucceeded = defineRule({
export const actionSucceeded = defineAutomation({
event: Event.actionSucceeded,
display: {
icon: CheckCircle,
Expand All @@ -60,7 +60,7 @@ export const actionSucceeded = defineRule({
});
export type ActionSucceeded = typeof actionSucceeded;

export const actionFailed = defineRule({
export const actionFailed = defineAutomation({
event: Event.actionFailed,
display: {
icon: XCircle,
Expand All @@ -70,25 +70,28 @@ export const actionFailed = defineRule({
});
export type ActionFailed = typeof actionFailed;

export const constructWebhookUrl = (ruleId: RulesId, communitySlug: string) =>
`/api/v0/c/${communitySlug}/site/webhook/${ruleId}`;
export const constructWebhookUrl = (automationId: AutomationsId, communitySlug: string) =>
`/api/v0/c/${communitySlug}/site/webhook/${automationId}`;

export const webhook = defineRule({
export const webhook = defineAutomation({
event: Event.webhook,
display: {
icon: Globe,
base: ({ community }) => (
<span>
a request is made to{" "}
<code>{constructWebhookUrl("<ruleId>" as RulesId, community.slug)}</code>
<code>
{constructWebhookUrl("<automationId>" as AutomationsId, community.slug)}
</code>
</span>
),
hydrated: ({ rule, community }) => (
hydrated: ({ automation: automation, community }) => (
<span>
a request is made to <code>{constructWebhookUrl(rule.id, community.slug)}</code>
a request is made to{" "}
<code>{constructWebhookUrl(automation.id, community.slug)}</code>
<CopyButton
value={new URL(
constructWebhookUrl(rule.id, community.slug),
constructWebhookUrl(automation.id, community.slug),
window.location.origin
).toString()}
/>
Expand All @@ -97,7 +100,7 @@ export const webhook = defineRule({
},
});

export type Rules =
export type Automation =
| PubInStageForDuration
| PubLeftStage
| PubEnteredStage
Expand All @@ -109,13 +112,15 @@ export type SchedulableEvent =
| Event.actionFailed
| Event.actionSucceeded;

export type RuleForEvent<E extends Event> = E extends E ? Extract<Rules, { event: E }> : never;
export type AutomationForEvent<E extends Event> = E extends E
? Extract<Automation, { event: E }>
: never;

export type SchedulableRule = RuleForEvent<SchedulableEvent>;
export type SchedulableAutomation = AutomationForEvent<SchedulableEvent>;

export type RuleConfig<Rule extends Rules = Rules> = Rule extends Rule
export type AutomationConfig<A extends Automation = Automation> = A extends A
? {
ruleConfig: NonNullable<Rule["additionalConfig"]>["_input"] extends infer RC
automationConfig: NonNullable<A["additionalConfig"]>["_input"] extends infer RC
? undefined extends RC
? null
: RC
Expand All @@ -124,4 +129,4 @@ export type RuleConfig<Rule extends Rules = Rules> = Rule extends Rule
}
: never;

export type RuleConfigs = RuleConfig | undefined;
export type AutomationConfigs = AutomationConfig | undefined;
10 changes: 5 additions & 5 deletions core/actions/_lib/runActionInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ import { env } from "~/lib/env/env";
import { createLastModifiedBy } from "~/lib/lastModifiedBy";
import { ApiError, getPubsWithRelatedValues } from "~/lib/server";
import { getActionConfigDefaults } from "~/lib/server/actions";
import { MAX_STACK_DEPTH } from "~/lib/server/automations";
import { autoRevalidate } from "~/lib/server/cache/autoRevalidate";
import { getCommunity } from "~/lib/server/community";
import { MAX_STACK_DEPTH } from "~/lib/server/rules";
import { isClientExceptionOptions } from "~/lib/serverActions";
import { getActionByName } from "../api";
import { ActionConfigBuilder } from "./ActionConfigBuilder";
Expand Down Expand Up @@ -375,13 +375,13 @@ export const runInstancesForEvent = async (
) => {
const instances = await trx
.selectFrom("action_instances")
.innerJoin("rules", "rules.actionInstanceId", "action_instances.id")
.innerJoin("automations", "automations.actionInstanceId", "action_instances.id")
.select([
"action_instances.id as actionInstanceId",
"rules.config as ruleConfig",
"automations.config as automationConfig",
"action_instances.name as actionInstanceName",
])
.where("rules.event", "=", event)
.where("automations.event", "=", event)
.where("action_instances.stageId", "=", stageId)
.execute();

Expand All @@ -396,7 +396,7 @@ export const runInstancesForEvent = async (
communityId,
actionInstanceId: instance.actionInstanceId,
event,
actionInstanceArgs: instance.ruleConfig ?? null,
actionInstanceArgs: instance.automationConfig ?? null,
stack,
},
trx
Expand Down
74 changes: 37 additions & 37 deletions core/actions/_lib/scheduleActionInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import type { ActionInstancesId, ActionRunsId, PubsId, StagesId } from "db/publi
import { ActionRunStatus, Event } from "db/public";
import { logger } from "logger";

import type { SchedulableRule } from "./rules";
import type { GetEventRuleOptions } from "~/lib/db/queries";
import type { SchedulableAutomation } from "./automations";
import type { GetEventAutomationOptions } from "~/lib/db/queries";
import { db } from "~/kysely/database";
import { addDuration } from "~/lib/dates";
import { getStageRules } from "~/lib/db/queries";
import { getStageAutomations } from "~/lib/db/queries";
import { autoRevalidate } from "~/lib/server/cache/autoRevalidate";
import { getCommunitySlug } from "~/lib/server/cache/getCommunitySlug";
import { getJobsClient, getScheduledActionJobKey } from "~/lib/server/jobs";
Expand All @@ -17,7 +17,7 @@ type Shared = {
stack: ActionRunsId[];
/* Config for the action instance */
config?: Record<string, unknown> | null;
} & GetEventRuleOptions;
} & GetEventAutomationOptions;

type ScheduleActionInstanceForPubOptions = Shared & {
pubId: PubsId;
Expand All @@ -42,85 +42,85 @@ export const scheduleActionInstances = async (options: ScheduleActionInstanceOpt
throw new Error("PubId or body is required");
}

const [rules, jobsClient] = await Promise.all([
getStageRules(options.stageId, options).execute(),
const [automations, jobsClient] = await Promise.all([
getStageAutomations(options.stageId, options).execute(),
getJobsClient(),
]);

if (!rules.length) {
if (!automations.length) {
logger.debug({
msg: `No action instances found for stage ${options.stageId}. Most likely this is because a Pub is moved into a stage without action instances.`,
pubId: options.pubId,
stageId: options.stageId,
rules,
automations,
});
return;
}

const validRules = rules
const validAutomations = automations
.filter(
(rule): rule is typeof rule & SchedulableRule =>
rule.event === Event.actionFailed ||
rule.event === Event.actionSucceeded ||
rule.event === Event.webhook ||
(rule.event === Event.pubInStageForDuration &&
(automation): automation is typeof automation & SchedulableAutomation =>
automation.event === Event.actionFailed ||
automation.event === Event.actionSucceeded ||
automation.event === Event.webhook ||
(automation.event === Event.pubInStageForDuration &&
Boolean(
typeof rule.config === "object" &&
rule.config &&
"duration" in rule.config &&
rule.config.duration &&
"interval" in rule.config &&
rule.config.interval
typeof automation.config === "object" &&
automation.config &&
"duration" in automation.config &&
automation.config.duration &&
"interval" in automation.config &&
automation.config.interval
))
)
.map((rule) => ({
...rule,
duration: rule.config?.ruleConfig?.duration || 0,
interval: rule.config?.ruleConfig?.interval || "minute",
.map((automation) => ({
...automation,
duration: automation.config?.automationConfig?.duration || 0,
interval: automation.config?.automationConfig?.interval || "minute",
}));

const results = await Promise.all(
validRules.flatMap(async (rule) => {
validAutomations.flatMap(async (automation) => {
const runAt = addDuration({
duration: rule.duration,
interval: rule.interval,
duration: automation.duration,
interval: automation.interval,
}).toISOString();

const scheduledActionRun = await autoRevalidate(
db
.insertInto("action_runs")
.values({
actionInstanceId: rule.actionInstance.id,
actionInstanceId: automation.actionInstance.id,
pubId: options.pubId,
json: options.json,
status: ActionRunStatus.scheduled,
config: options.config ?? rule.actionInstance.config,
config: options.config ?? automation.actionInstance.config,
result: { scheduled: `Action scheduled for ${runAt}` },
event: rule.event,
event: automation.event,
sourceActionRunId: options.stack.at(-1),
})
.returning("id")
).executeTakeFirstOrThrow();

const job = await jobsClient.scheduleAction({
actionInstanceId: rule.actionInstance.id,
duration: rule.duration,
interval: rule.interval,
actionInstanceId: automation.actionInstance.id,
duration: automation.duration,
interval: automation.interval,
stageId: options.stageId,
community: {
slug: await getCommunitySlug(),
},
stack: options.stack,
scheduledActionRunId: scheduledActionRun.id,
event: rule.event,
event: automation.event,
...(options.pubId ? { pubId: options.pubId } : { json: options.json! }),
config: options.config ?? rule.actionInstance.config ?? null,
config: options.config ?? automation.actionInstance.config ?? null,
});

return {
result: job,
actionInstanceId: rule.actionInstance.id,
actionInstanceName: rule.actionInstance.name,
actionInstanceId: automation.actionInstance.id,
actionInstanceName: automation.actionInstance.name,
runAt,
};
})
Expand Down
Loading
Loading