import { DEFAULT_POLLING_SOURCE_TIMER_INTERVAL } from "@pipedream/platform";
import differenceBy from "lodash.differenceby";
import pagerduty from "../../pagerduty.app.mjs";
import common from "../common.mjs";
export default {
...common,
key: "pagerduty-new-oncall-rotation",
name: "New On-Call Rotation",
version: "0.1.1",
description: "Emit new event each time a new user rotates onto an on-call rotation",
type: "source",
props: {
...common.props,
pagerduty,
db: "$.service.db",
escalationPoliciesIds: {
type: "string[]",
label: "Escalation Policies",
description: "To filter your on-call rotations to specific escalation policies, select them here. **To listen for rotations across all escalation policies, leave this blank**.",
propDefinition: [
pagerduty,
"escalationPolicyId",
],
},
timer: {
type: "$.interface.timer",
label: "Interval to poll for new rotations",
description:
"The PagerDuty API doesn't support webhook notifications for on-call rotations, so we must poll the API to check for these changes. Change this interval according to your needs.",
default: {
intervalSeconds: DEFAULT_POLLING_SOURCE_TIMER_INTERVAL,
},
},
},
async run() {
const escalationPoliciesIds =
this.escalationPoliciesIds?.length
? this.escalationPoliciesIds
: await this.pagerduty.listEscalationPoliciesIds();
const oncallUsersByEscalationPolicy = this.getOncallUsersByEscalationPolicy() || {};
for (const escalationPolicyId of escalationPoliciesIds) {
const oncallUsers = await this.pagerduty.listOncallUsers({
params: {
escalation_policy_ids: [
escalationPolicyId,
],
},
});
const previousUsersOncall = oncallUsersByEscalationPolicy[escalationPolicyId] || [];
const newOncallUsers = differenceBy(
oncallUsers,
previousUsersOncall,
"id",
);
oncallUsersByEscalationPolicy[escalationPolicyId] = oncallUsers;
if (!newOncallUsers.length) {
console.log(`No change to on-call users for escalation policy ${escalationPolicyId}`);
continue;
}
const escalationPolicy =
await this.pagerduty.getEscalationPolicy({
escalationPolicyId,
});
newOncallUsers.forEach((user) => {
this.$emit({
user,
escalationPolicy,
}, {
summary: `${user.summary} is now on-call for escalation policy ${escalationPolicy.name}`,
});
});
}
this.setOncallUsersByEscalationPolicy(oncallUsersByEscalationPolicy);
},
};