Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.4 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  StoreScope,
  Property,
  isNil,
} from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { plausibleAuth } from '../..';
import { plausibleApiCall, siteIdDropdown } from '../common';

export const trafficSpike = createTrigger({
  name: 'traffic_spike',
  auth: plausibleAuth,
  displayName: 'Traffic Spike',
  description:
    'Triggers once when current visitors exceed a threshold, then resets when they drop below it',
  aiMetadata: {
    description: 'Fires once when a site\'s real-time visitor count crosses above a configured threshold, representing the onset of a traffic spike. It does not fire again until the count drops back below the threshold and then rises above it once more, so each sustained spike yields a single event.',
  },
  type: TriggerStrategy.POLLING,
  props: {
    site_id: siteIdDropdown,
    threshold: Property.Number({
      displayName: 'Visitor Threshold',
      description: 'Trigger when visitors exceed this number',
      required: true,
      defaultValue: 100,
    }),
  },
  async onEnable({ store, isRepublish }) {
    if (
      isRepublish &&
      !isNil(await store.get('wasAboveThreshold', StoreScope.FLOW))
    ) {
      return;
    }
    await store.put('wasAboveThreshold', false, StoreScope.FLOW);
  },
  async onDisable({ store, isRepublish }) {
    if (isRepublish) {
      return;
    }
    await store.delete('wasAboveThreshold', StoreScope.FLOW);
  },
  async run({ auth, propsValue, store }) {
    const visitors = await plausibleApiCall<number>({
      apiKey: auth.secret_text,
      method: HttpMethod.GET,
      endpoint: '/stats/realtime/visitors',
      queryParams: { site_id: propsValue.site_id },
    });

    const threshold = propsValue.threshold ?? 100;
    const isAbove = visitors >= threshold;
    const wasAbove = await store.get<boolean>('wasAboveThreshold', StoreScope.FLOW);

    await store.put('wasAboveThreshold', isAbove, StoreScope.FLOW);

    if (isAbove && !wasAbove) {
      return [
        {
          site_id: propsValue.site_id,
          current_visitors: visitors,
          threshold,
          triggered_at: new Date().toISOString(),
        },
      ];
    }
    return [];
  },
  sampleData: {
    site_id: 'example.com',
    current_visitors: 150,
    threshold: 100,
    triggered_at: '2024-01-01T12:00:00Z',
  },
});