0

Task Run Trigger (for polling)

Published today

Retrieves the latest runs of a selected Apify Task and returns their details if they are new runs (compared to last poll) and has completed with one of the specified terminal statuses. Intended for use with Windmill's native polling trigger, which handles the periodic execution and state management. First run always returns an empty array. An empty array is also returned after "Task ID" and/or "Event Types" are changed.

Script· trigger apify Verified

The script

Submitted by jakub.drobnik222 Bun
Verified 3 hours ago
1
import * as wmill from 'windmill-client';
2

3
import { ApifyClient } from 'apify-client@^2.19.0';
4

5
type ApifyApiKey = {
6
  api_key: string;
7
};
8

9
type Apify = {
10
  token: string;
11
};
12

13
type EventType = 'SUCCEEDED' | 'FAILED' | 'TIMED-OUT' | 'ABORTED';
14

15
export type DynSelect_taskId = string;
16
export async function taskId(api_key?: ApifyApiKey, oauth_token?: Apify) {
17
  if (!api_key?.api_key && !oauth_token?.token) {
18
    return [{ value: '', label: 'Missing Apify API key or OAuth token' }];
19
  }
20

21
  try {
22
    const client = createClient(api_key, oauth_token);
23

24
    const data = await client.tasks().list();
25
    const items = data?.items ?? [];
26

27
    return items.map((task: any) => ({
28
      value: task.id,
29
      label: task.title || task.name || task.id,
30
    }));
31
  } catch (error: any) {
32
    return [
33
      { value: '', label: `Failed to load tasks: ${error.message || error}` },
34
    ];
35
  }
36
}
37

38
const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => {
39
  const token = oauth_token?.token ?? api_key?.api_key;
40
  if (!token) {
41
    throw new Error('Missing Apify API key or OAuth token');
42
  }
43

44
  return new ApifyClient({
45
    token: token,
46
    requestInterceptors: [
47
      (request) => {
48
        if (!request.headers) {
49
          request.headers = {};
50
        }
51
        request.headers['x-apify-integration-platform'] = 'windmill';
52
        return request;
53
      },
54
    ],
55
  });
56
};
57

58
function areEventTypesEqual(a?: EventType[], b?: EventType[]): boolean {
59
  if (!a || !b) return false;
60
  return JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
61
}
62

63
type TriggerState = {
64
  lastRunId?: string;
65
  taskId?: string;
66
  eventTypes?: EventType[];
67
};
68

69
// -----------------------------------------------------------------------------
70
// main logic
71
export async function main(
72
  taskId: DynSelect_taskId,
73
  eventTypes: EventType[],
74
  runsLimit: number,
75
  api_key?: ApifyApiKey,
76
  oauth_token?: Apify,
77
) {
78
  // Validate event types
79
  if (!eventTypes.length) {
80
    return { error: 'At least one of the Event Types has to be picked.' };
81
  }
82

83
  // Validate runsLimit to be a positive integer and cap at 1000
84
  const validatedRunsLimit = Number.isFinite(Number(runsLimit))
85
    ? Math.min(1000, Math.floor(Number(runsLimit)))
86
    : NaN;
87

88
  if (!validatedRunsLimit || validatedRunsLimit < 1) {
89
    return { error: 'runsLimit must be a positive integer.' };
90
  }
91

92
  try {
93
    const client = createClient(api_key, oauth_token);
94

95
    // Fetch runs using the provided runsLimit (can return multiple)
96
    const { items } = await client.task(taskId).runs().list({
97
      limit: validatedRunsLimit,
98
      offset: 0,
99
      desc: true, // newest first
100
      status: eventTypes,
101
    });
102

103
    // Fetched runs array
104
    const runs: any[] = items ?? [];
105

106
    // Get persisted state
107
    const state = (await wmill.getState()) as TriggerState | undefined;
108
    const newestRunId: string | undefined = runs[0]?.id;
109

110
    // Check if task or event types changed since last time
111
    const taskChanged = state?.taskId !== taskId;
112
    const eventTypesChanged = !areEventTypesEqual(state?.eventTypes, eventTypes);
113

114
    // First-ever run, or task or event types changed: only persist the newest
115
    // run's ID and return an empty array. The state is saved even when there are
116
    // no runs yet, so the next poll returns the first matching run instead of
117
    // treating it as the first-ever run.
118
    if (!state || taskChanged || eventTypesChanged) {
119
      await wmill.setState({
120
        lastRunId: newestRunId,
121
        taskId: taskId,
122
        eventTypes,
123
      });
124
      return [];
125
    }
126

127
    // If nothing returned, skip
128
    if (runs.length === 0) {
129
      return [];
130
    }
131

132
    // Find index of the previously processed run (none if there were no runs
133
    // when the state was saved, so all fetched runs are new)
134
    const lastRunId = state.lastRunId;
135
    const foundIdx = lastRunId ? runs.findIndex((run) => run?.id === lastRunId) : -1;
136

137
    // If found, return only the newer runs to the left; otherwise return all
138
    const newerRuns = foundIdx >= 0 ? runs.splice(0, foundIdx) : runs;
139

140
    // Persist the newest run ID + metadata for next trigger
141
    await wmill.setState({
142
      lastRunId: newestRunId,
143
      taskId: taskId,
144
      eventTypes,
145
    });
146

147
    // Return array of newer runs (which can be empty if foundIdx is 0)
148
    return newerRuns;
149
  } catch (error: any) {
150
    return {
151
      error: `Failed to process task trigger. Reason: ${
152
        error?.message || error
153
      }`,
154
    };
155
  }
156
}