@polarityio/integration-types 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/context.d.ts CHANGED
@@ -261,6 +261,41 @@ export interface IntegrationContext {
261
261
  limiter: Limiter;
262
262
  /** Per-integration network (TLS/proxy) configuration provided by the runtime on every dispatch. */
263
263
  network: NetworkContext;
264
- startPolling: (pollName: string) => void;
264
+ /**
265
+ * Starts a named poller that was defined in the integration's `poll` export.
266
+ *
267
+ * If the poller is already running, this call is a no-op.
268
+ *
269
+ * @param pollName - The key from the integration's `poll` record identifying
270
+ * which poller to start.
271
+ * @param runImmediately - When `true` (default), the poll function fires once
272
+ * immediately before the first scheduled interval or cron tick. When `false`,
273
+ * the first execution waits for the next scheduled tick.
274
+ *
275
+ * @example Start a poller and fire immediately
276
+ * ```typescript
277
+ * context.startPolling('refreshTokens');
278
+ * ```
279
+ *
280
+ * @example Start a poller but wait for the first scheduled tick
281
+ * ```typescript
282
+ * context.startPolling('weeklyReport', false);
283
+ * ```
284
+ */
285
+ startPolling: (pollName: string, runImmediately?: boolean) => void;
286
+ /**
287
+ * Stops a named poller that is currently running.
288
+ *
289
+ * If the poller is not running, this call is a no-op. A stopped poller can be
290
+ * restarted later via `startPolling()`.
291
+ *
292
+ * @param pollName - The key from the integration's `poll` record identifying
293
+ * which poller to stop.
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * context.stopPolling('refreshTokens');
298
+ * ```
299
+ */
265
300
  stopPolling: (pollName: string) => void;
266
301
  }
package/dist/index.d.ts CHANGED
@@ -5,5 +5,5 @@ export type { CacheOptions, GlobalCache, IntegrationCache, UserCache, PolarityCa
5
5
  export type { ThrottleStrategy, ScheduleOptions, LimiterCounts, ThrottleSettings, ScopedLimiter, Limiter } from './limiter';
6
6
  export type { Logger } from './logger';
7
7
  export type { Integration } from './integration';
8
- export type { PollFunction, IntervalPollSpec, CronPollSpec, PollSpec, Poll } from './polling';
8
+ export type { PollFunction, PollFailureStrategy, IntervalPollSpec, CronPollSpec, PollSpec, Poll } from './polling';
9
9
  export type { TextOption, BooleanOption, NumberOption, SelectOption, IntegrationOption, LogLevel, RequestConfig, IntegrationConfig } from './config';
package/dist/polling.d.ts CHANGED
@@ -1,68 +1,219 @@
1
1
  import type { DoLookupUserOptions } from './user-options';
2
2
  import type { IntegrationContext } from './context';
3
3
  /**
4
- * A function that is called on a polling schedule.
4
+ * The function invoked on each poll cycle (interval tick or cron trigger).
5
5
  *
6
- * Receives admin-only (global) user options and the integration context.
6
+ * Receives admin-only user options (matching the integration's `config.json` shape)
7
+ * and the full integration context. The function should perform its work and return
8
+ * without a meaningful value — any returned value is discarded by the runtime.
9
+ *
10
+ * ### Execution Model
11
+ *
12
+ * Poll functions run in a **dedicated polling worker** that is separate from the
13
+ * integration workers handling `doLookup`, `onMessage`, and `onDetails` dispatches.
14
+ * Each poll function executes **once per integration** — not once per worker instance.
15
+ * This means poll functions are singletons: even if multiple integration workers are
16
+ * running, only one instance of each poller is active at any time.
17
+ *
18
+ * Because the polling worker is isolated, poll functions do not share in-memory state
19
+ * with integration dispatch workers. Use `context.cache` to exchange data between
20
+ * poll functions and dispatch handlers.
21
+ *
22
+ * @param options - Admin-only (global) user options for the integration.
23
+ * @param context - The integration context providing cache, logger, limiter, and network utilities.
7
24
  */
8
25
  export type PollFunction = (options: DoLookupUserOptions, context: IntegrationContext) => Promise<void>;
26
+ /**
27
+ * Strategy the runtime uses when a poll function throws an unhandled error.
28
+ *
29
+ * - `'retry'` — The runtime catches the error and retries the poll function on
30
+ * the next scheduled tick. Useful for transient failures (e.g., network timeouts).
31
+ * - `'shutdown'` — The runtime stops the integration entirely and surfaces the
32
+ * error to the Polarity frontend. Use for unrecoverable failures where continued
33
+ * polling would be harmful.
34
+ * - `'skip'` — The runtime logs the error and continues polling on its normal schedule (no retry is performed for the failed run). Use when individual poll failures are acceptable and polling should continue uninterrupted.
35
+ */
36
+ export type PollFailureStrategy = 'retry' | 'shutdown' | 'skip';
37
+ /**
38
+ * Shared configuration for all poll specifications.
39
+ */
9
40
  interface BasePollSpec {
10
- /** The function to call on each poll cycle. */
41
+ /**
42
+ * The function to invoke on each poll cycle.
43
+ *
44
+ * @see {@link PollFunction}
45
+ */
11
46
  function: PollFunction;
12
47
  /**
13
- * Whether to start polling automatically when the integration loads.
14
- * If `false`, polling must be started manually via `context.startPolling()`.
48
+ * Whether to start this poller automatically when the integration is loaded
49
+ * by the runtime.
50
+ *
51
+ * - `true` — Polling begins immediately after the integration's `startup`
52
+ * hook completes.
53
+ * - `false` (default) — Polling does not begin until explicitly started via
54
+ * `context.startPolling(pollName)`.
55
+ *
56
+ * @default false
15
57
  */
16
58
  autostart?: boolean;
17
59
  /**
18
- * Strategy to use when the poll function throws an error.
60
+ * Whether to execute the poll function immediately when the poller starts,
61
+ * before waiting for the first interval tick or cron trigger.
62
+ *
63
+ * - `true` — The poll function fires once immediately on start, then
64
+ * continues on its normal schedule.
65
+ * - `false` (default) — The first execution occurs after the first
66
+ * interval/cron tick.
19
67
  *
20
- * - `'restart'` — Retry the function with linear backoff until it succeeds,
21
- * then resume the normal schedule.
22
- * - `'shutdown'` — Stop the integration and report an error to the frontend.
68
+ * This applies to automatic start (when `autostart` is `true`). When a poller
69
+ * is started manually via `context.startPolling()`, the method's own
70
+ * `runImmediately` parameter takes precedence over this spec-level value.
71
+ *
72
+ * @default false
73
+ */
74
+ runImmediately?: boolean;
75
+ /**
76
+ * Strategy to use when the poll function throws an unhandled error.
77
+ *
78
+ * @default 'retry'
79
+ * @see {@link PollFailureStrategy}
23
80
  */
24
- failureStrategy?: 'restart' | 'shutdown';
81
+ failureStrategy?: PollFailureStrategy;
25
82
  }
26
83
  /**
27
- * A poll specification that runs on a fixed interval.
84
+ * A poll specification that runs on a fixed time interval.
85
+ *
86
+ * The interval defines the delay **between** the completion of one invocation
87
+ * and the start of the next — not a fixed-rate schedule. If the poll function
88
+ * takes longer than the interval, executions will not overlap.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const spec: IntervalPollSpec = {
93
+ * function: doRefreshTokens,
94
+ * interval: 60, // every 60 seconds
95
+ * autostart: true,
96
+ * runImmediately: true, // fire once immediately on start
97
+ * failureStrategy: 'retry'
98
+ * };
99
+ * ```
28
100
  */
29
101
  export interface IntervalPollSpec extends BasePollSpec {
30
- /** Polling interval in milliseconds. */
102
+ /**
103
+ * Polling interval in **seconds**.
104
+ *
105
+ * Must be a positive number. The runtime waits this many seconds after the
106
+ * previous invocation completes before starting the next one.
107
+ */
31
108
  interval: number;
109
+ /** @internal Discriminator — `cron` is not allowed on interval-based specs. */
32
110
  cron?: never;
33
111
  }
34
112
  /**
35
113
  * A poll specification that runs on a cron schedule.
114
+ *
115
+ * Uses standard 5-field cron syntax (`minute hour day-of-month month day-of-week`).
116
+ * All times are evaluated in UTC.
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const spec: CronPollSpec = {
121
+ * function: doWeeklyReport,
122
+ * cron: '0 9 * * 1', // every Monday at 09:00 UTC
123
+ * failureStrategy: 'shutdown'
124
+ * };
125
+ * ```
36
126
  */
37
127
  export interface CronPollSpec extends BasePollSpec {
38
- /** A cron expression defining the polling schedule (e.g., `"0 9 * * *"`). */
128
+ /**
129
+ * A cron expression defining the polling schedule.
130
+ *
131
+ * Uses standard 5-field syntax: `minute hour day-of-month month day-of-week`.
132
+ * All times are evaluated in UTC.
133
+ *
134
+ * Common patterns:
135
+ * - `'0 9 * * *'` — daily at 09:00 UTC
136
+ * - `'0 0 * * 6'` — every Saturday at midnight UTC
137
+ * - `'0/5 * * * *'` — every 5 minutes (step syntax)
138
+ */
39
139
  cron: string;
140
+ /** @internal Discriminator — `interval` is not allowed on cron-based specs. */
40
141
  interval?: never;
41
142
  }
42
143
  /**
43
144
  * A single poll specification — either interval-based or cron-based.
145
+ *
146
+ * Use {@link IntervalPollSpec} for fixed-delay polling (e.g., every 30 seconds)
147
+ * or {@link CronPollSpec} for calendar-based scheduling (e.g., daily at 9 AM).
148
+ *
149
+ * These two forms are mutually exclusive: a spec must define either `interval`
150
+ * or `cron`, but never both.
44
151
  */
45
152
  export type PollSpec = IntervalPollSpec | CronPollSpec;
46
153
  /**
47
154
  * A record of named poll specifications exported by an integration.
48
155
  *
49
- * Each key is the poll name (used with `context.startPolling()` / `context.stopPolling()`),
50
- * and the value defines the schedule and function to call.
156
+ * Each key is the **poll name** — a unique identifier used with
157
+ * `context.startPolling()` and `context.stopPolling()` to manually control
158
+ * individual pollers at runtime.
51
159
  *
52
- * @example
160
+ * ### Runtime Behavior
161
+ *
162
+ * Pollers execute in a **dedicated polling worker** that is independent of the
163
+ * integration workers handling lookup and message dispatches. Regardless of how
164
+ * many integration worker instances are running, each poller runs exactly **once
165
+ * per integration** — ensuring that scheduled tasks (e.g., token refresh, report
166
+ * generation) are not duplicated across workers.
167
+ *
168
+ * @example Basic polling configuration
53
169
  * ```typescript
170
+ * import type { Poll } from '@polarityio/integration-types';
171
+ *
54
172
  * const poll: Poll = {
55
173
  * refreshTokens: {
56
174
  * function: doRefreshTokens,
57
- * interval: 10000,
58
- * autostart: true
175
+ * interval: 30, // every 30 seconds
176
+ * autostart: true,
177
+ * runImmediately: true
59
178
  * },
60
- * uploadReport: {
61
- * function: doUploadReport,
62
- * cron: "0 9 * * *",
63
- * failureStrategy: "restart"
179
+ * weeklyReport: {
180
+ * function: doWeeklyReport,
181
+ * cron: '0 9 * * 1', // Mondays at 09:00 UTC
182
+ * failureStrategy: 'shutdown'
64
183
  * }
65
184
  * };
185
+ *
186
+ * export { poll };
187
+ * ```
188
+ *
189
+ * @example One-time initialization pattern
190
+ *
191
+ * Because poll functions are singletons (one instance per integration), you can
192
+ * use a poller with `runImmediately: true` and `autostart: true` to guarantee a
193
+ * function runs exactly once across all integration workers. The function stops
194
+ * itself after the first execution by calling `context.stopPolling()`.
195
+ *
196
+ * ```typescript
197
+ * import type { Poll, PollFunction } from '@polarityio/integration-types';
198
+ *
199
+ * const initializeOnce: PollFunction = async (options, context) => {
200
+ * // Perform one-time setup (e.g., seed cache, register webhooks)
201
+ * await seedIntegrationCache(options, context);
202
+ *
203
+ * // Stop the poller — this function will never run again
204
+ * context.stopPolling('initialize');
205
+ * };
206
+ *
207
+ * const poll: Poll = {
208
+ * initialize: {
209
+ * function: initializeOnce,
210
+ * interval: 60, // interval is required but irrelevant here
211
+ * autostart: true,
212
+ * runImmediately: true // fire immediately on integration load
213
+ * }
214
+ * };
215
+ *
216
+ * export { poll };
66
217
  * ```
67
218
  */
68
219
  export type Poll = Record<string, PollSpec>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polarityio/integration-types",
3
- "version": "2.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "TypeScript type definitions for Polarity Integrations",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {