0

Actor Run Trigger (for polling)

Published today

Retrieves the latest runs of a selected Apify Actor 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 "Actor 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 { ActorListSortBy, 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
type ActorSource = 'RECENTLY_USED_ACTORS' | 'APIFY_STORE_ACTORS';
16

17
export type DynSelect_actorId = string;
18
export async function actorId(actorSource: ActorSource, api_key?: ApifyApiKey, oauth_token?: Apify) {
19
  if (!api_key?.api_key && !oauth_token?.token) {
20
    return [{ value: '', label: 'Missing Apify API key or OAuth token' }];
21
  }
22

23
  const client = createClient(api_key, oauth_token);
24

25
  const mapActorToSelectOption = (actor: any) => {
26
    const optionName = actor.title
27
      ? `${actor.title} (${actor.username}/${actor.name})`
28
      : `${actor.username}/${actor.name}`;
29

30
    return {
31
      label: optionName,
32
      value: actor.id,
33
    };
34
  };
35

36
  try {
37
    if (actorSource === 'RECENTLY_USED_ACTORS') {
38
      const recentActors = await client.actors().list({
39
        limit: 100,
40
        offset: 0,
41
        sortBy: ActorListSortBy.LAST_RUN_STARTED_AT,
42
        desc: true,
43
      });
44
      return recentActors.items.map(mapActorToSelectOption);
45
    }
46

47
    const storeActors = await client.store().list({
48
      limit: 1000,
49
      offset: 0,
50
    });
51
    return storeActors.items.map(mapActorToSelectOption);
52
  } catch (error: any) {
53
    return [
54
      { value: '', label: `Failed to load actors: ${error.message || error}` },
55
    ];
56
  }
57
}
58

59
const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => {
60
  const token = oauth_token?.token ?? api_key?.api_key;
61
  if (!token) {
62
    throw new Error('Missing Apify API key or OAuth token');
63
  }
64

65
  return new ApifyClient({
66
    token: token,
67
    requestInterceptors: [
68
      (request) => {
69
        if (!request.headers) {
70
          request.headers = {};
71
        }
72
        request.headers['x-apify-integration-platform'] = 'windmill';
73
        return request;
74
      },
75
    ],
76
  });
77
};
78

79
function areEventTypesEqual(a?: EventType[], b?: EventType[]): boolean {
80
  if (!a || !b) return false;
81
  return JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
82
}
83

84
type TriggerState = {
85
  lastRunId?: string;
86
  actorId?: string;
87
  eventTypes?: EventType[];
88
};
89

90
// -----------------------------------------------------------------------------
91
// main logic
92
export async function main(
93
  actorSource: ActorSource,
94
  actorId: DynSelect_actorId,
95
  eventTypes: EventType[],
96
  runsLimit: number,
97
  api_key?: ApifyApiKey,
98
  oauth_token?: Apify,
99
) {
100
  if (!eventTypes.length) {
101
    return { error: 'At least one of the Event Types has to be picked.' };
102
  }
103

104
  // Validate runsLimit to be a positive integer and cap at 1000
105
  const validatedRunsLimit = Number.isFinite(Number(runsLimit))
106
    ? Math.min(1000, Math.floor(Number(runsLimit)))
107
    : NaN;
108

109
  if (!validatedRunsLimit || validatedRunsLimit < 1) {
110
    return { error: 'runsLimit must be a positive integer.' };
111
  }
112

113
  try {
114
    const client = createClient(api_key, oauth_token);
115

116
    const { items } = await client.actor(actorId).runs().list({
117
      limit: validatedRunsLimit,
118
      offset: 0,
119
      desc: true,
120
      status: eventTypes,
121
    });
122

123
    const runs: any[] = items ?? [];
124

125
    // Get persisted state
126
    const state = (await wmill.getState()) as TriggerState | undefined;
127
    const newestRunId: string | undefined = runs[0]?.id;
128

129
    // Check if actor or event types changed since last time
130
    const actorChanged = state?.actorId !== actorId;
131
    const eventTypesChanged = !areEventTypesEqual(state?.eventTypes, eventTypes);
132

133
    // First-ever run, or actor or event types changed: only persist the newest
134
    // run's ID and return an empty array. The state is saved even when there are
135
    // no runs yet, so the next poll returns the first matching run instead of
136
    // treating it as the first-ever run.
137
    if (!state || actorChanged || eventTypesChanged) {
138
      await wmill.setState({
139
        lastRunId: newestRunId,
140
        actorId: actorId,
141
        eventTypes: eventTypes,
142
      });
143
      return [];
144
    }
145

146
    // If nothing returned, skip
147
    if (runs.length === 0) {
148
      return [];
149
    }
150

151
    // Find index of the previously processed run (none if there were no runs
152
    // when the state was saved, so all fetched runs are new)
153
    const lastRunId = state.lastRunId;
154
    const foundIdx = lastRunId ? runs.findIndex((r) => r?.id === lastRunId) : -1;
155

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

159
    // Persist the newest run ID + metadata for next trigger
160
    await wmill.setState({
161
      lastRunId: newestRunId,
162
      actorId: actorId,
163
      eventTypes: eventTypes,
164
    });
165

166
    // Return array of newer runs (which can be empty if foundIdx is 0)
167
    return newerRuns;
168
  } catch (error: any) {
169
    return {
170
      error: `Failed to process actor trigger. Reason: ${error.message || error
171
        }`,
172
    };
173
  }
174
}