@friggframework/core 2.0.0--canary.693.d8859c2.0 → 2.0.0--canary.694.f66a64a.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.
@@ -25,6 +25,8 @@ async function findMany(client, collection, filter = {}, options = {}) {
25
25
  if (options.projection) command.projection = options.projection;
26
26
  if (options.sort) command.sort = options.sort;
27
27
  if (options.limit) command.limit = options.limit;
28
+ // The first batch holds 101 documents unless asked for more; a page wants all of its rows.
29
+ if (options.batchSize) command.batchSize = options.batchSize;
28
30
  const result = await client.$runCommandRaw(command);
29
31
  return result?.cursor?.firstBatch || [];
30
32
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The `{integration}Triggers` functions (ADR-055 §2-3): one per integration that declares triggers. Devtools gives
3
+ * each one schedule per distinct tick (`{ tick: '5m', time }`) and one per `at` trigger (`{ at, time }`); this only
4
+ * hands the event to the tick use case.
5
+ */
6
+ const { createHandler } = require('@friggframework/core');
7
+ const { loadAppDefinition } = require('../app-definition-loader');
8
+ const { hasTriggers } = require('../../integrations/triggers');
9
+ const { runTriggerTick } = require('../../integrations/use-cases/run-trigger-tick');
10
+
11
+ const handlers = {};
12
+ const { integrations: integrationClasses } = loadAppDefinition();
13
+
14
+ for (const IntegrationClass of integrationClasses) {
15
+ if (!hasTriggers(IntegrationClass)) continue;
16
+ handlers[IntegrationClass.Definition.name] = {
17
+ tick: createHandler({
18
+ eventName: `Trigger tick for ${IntegrationClass.Definition.name}`,
19
+ isUserFacingResponse: false,
20
+ method: async (event, context) => runTriggerTick(IntegrationClass, event || {}, context),
21
+ }),
22
+ };
23
+ }
24
+
25
+ module.exports = { handlers };
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Recurrence: how often something repeats, in a form no host owns.
3
+ *
4
+ * { every: '15m' } every 15 minutes ('30s' is refused: ticks are whole minutes)
5
+ * { cron: '0 9 * * 1-5', timezone: 'America/New_York' } standard five-field cron (minute hour dom month dow)
6
+ *
7
+ * Recurring triggers (ADR-055, integrations/triggers.js) use it for the timing an installation may choose and for
8
+ * the floor a developer sets on that choice. Nothing here creates a host schedule: the tick asks `lastFiringIn`
9
+ * whether a cron fired since the previous tick, so a per-installation calendar needs no schedule of its own.
10
+ *
11
+ * Pure; no I/O.
12
+ */
13
+
14
+ const EVERY = /^(\d+)\s*(m|h|d)$/;
15
+ const UNIT_MINUTES = { m: 1, h: 60, d: 1440 };
16
+
17
+ /** '15m' -> 15, '2h' -> 120, '1d' -> 1440. Anything else -> null. */
18
+ function parseEvery(every) {
19
+ const m = EVERY.exec(String(every ?? '').trim());
20
+ if (!m) return null;
21
+ const n = Number(m[1]) * UNIT_MINUTES[m[2]];
22
+ return n > 0 ? n : null;
23
+ }
24
+
25
+ const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
26
+ const DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
27
+ const FIELDS = [
28
+ { name: 'minute', min: 0, max: 59 },
29
+ { name: 'hour', min: 0, max: 23 },
30
+ { name: 'day of month', min: 1, max: 31 },
31
+ { name: 'month', min: 1, max: 12, names: MONTHS, base: 1 },
32
+ { name: 'day of week', min: 0, max: 7, names: DAYS, base: 0 }, // 0 and 7 are both Sunday
33
+ ];
34
+
35
+ function atom(token, field) {
36
+ const t = token.toUpperCase();
37
+ if (field.names) {
38
+ const i = field.names.indexOf(t);
39
+ if (i >= 0) return i + field.base;
40
+ }
41
+ if (!/^\d+$/.test(t)) return null;
42
+ const n = Number(t);
43
+ return n >= field.min && n <= field.max ? n : null;
44
+ }
45
+
46
+ /** One cron field -> the sorted set of values it matches, or an error string. */
47
+ function parseField(text, field) {
48
+ const out = new Set();
49
+ for (const part of text.split(',')) {
50
+ const [range, stepText] = part.split('/');
51
+ if (part.split('/').length > 2) return `${field.name}: "${part}" has more than one step`;
52
+ const step = stepText === undefined ? 1 : Number(stepText);
53
+ if (!Number.isInteger(step) || step < 1) return `${field.name}: step "${stepText}" is not a positive whole number`;
54
+ let lo, hi;
55
+ if (range === '*') { lo = field.min; hi = field.name === 'day of week' ? 6 : field.max; }
56
+ else if (range.includes('-')) {
57
+ const [a, b] = range.split('-');
58
+ lo = atom(a, field); hi = atom(b, field);
59
+ if (lo === null || hi === null) return `${field.name}: "${range}" is out of range`;
60
+ if (lo > hi) return `${field.name}: "${range}" runs backwards`;
61
+ } else {
62
+ lo = atom(range, field);
63
+ if (lo === null) return `${field.name}: "${range}" is out of range`;
64
+ hi = stepText === undefined ? lo : (field.name === 'day of week' ? 6 : field.max);
65
+ }
66
+ for (let v = lo; v <= hi; v += step) out.add(field.name === 'day of week' && v === 7 ? 0 : v);
67
+ }
68
+ return [...out].sort((a, b) => a - b);
69
+ }
70
+
71
+ /**
72
+ * Parse a five-field cron. Returns { fields: [Set x5], restricted: { dom, dow } } or { error }.
73
+ * `restricted` records whether day-of-month / day-of-week were given (not `*`), which decides how they combine.
74
+ */
75
+ function parseCron(cron) {
76
+ const parts = String(cron ?? '').trim().split(/\s+/);
77
+ if (parts.length !== 5 || parts[0] === '') return { error: 'A cron expression has five fields: minute hour day-of-month month day-of-week' };
78
+ const fields = [];
79
+ for (let i = 0; i < 5; i += 1) {
80
+ const v = parseField(parts[i], FIELDS[i]);
81
+ if (typeof v === 'string') return { error: v };
82
+ fields.push(new Set(v));
83
+ }
84
+ return { fields, parts, restricted: { dom: parts[2] !== '*', dow: parts[4] !== '*' } };
85
+ }
86
+
87
+ /** Does a parsed cron fire at this (UTC-free, wall-clock) minute? Standard cron: dom and dow OR when both are set. */
88
+ function matches(parsed, d) {
89
+ const [mi, h, dom, mon, dow] = parsed.fields;
90
+ if (!mi.has(d.getUTCMinutes()) || !h.has(d.getUTCHours()) || !mon.has(d.getUTCMonth() + 1)) return false;
91
+ const domHit = dom.has(d.getUTCDate()), dowHit = dow.has(d.getUTCDay());
92
+ if (parsed.restricted.dom && parsed.restricted.dow) return domHit || dowHit;
93
+ return domHit && dowHit;
94
+ }
95
+
96
+ /**
97
+ * The shortest gap, in minutes, between two firings. For `every` it is the interval; for cron it is measured over
98
+ * fifteen months of wall-clock minutes (long enough to see every month and weekday combination), so a floor such as
99
+ * "no more often than every 15 minutes" is checked against what the expression really does, not its spelling.
100
+ * Returns Infinity for an expression that fires at most once in that window, null when invalid.
101
+ */
102
+ function minGapMinutes(recurrence) {
103
+ if (recurrence?.every !== undefined) return parseEvery(recurrence.every);
104
+ const parsed = parseCron(recurrence?.cron);
105
+ return parsed.error ? null : scan(parsed).best;
106
+ }
107
+
108
+ /** Walk fifteen months of firings: how many there are and the shortest gap between two. */
109
+ function scan(parsed) {
110
+ const [mi, h] = parsed.fields;
111
+ const minutes = [...mi], hours = [...h];
112
+ let prev = null, best = Infinity, count = 0;
113
+ const start = Date.UTC(2027, 0, 1);
114
+ for (let day = 0; day < 457 && best > 1; day += 1) { // fifteen months: every month and weekday pairing
115
+ const midnight = start + day * 86400000;
116
+ if (!matches(parsed, new Date(midnight + hours[0] * 3600000 + minutes[0] * 60000))) continue;
117
+ for (const hr of hours) {
118
+ for (const mn of minutes) {
119
+ const t = day * 1440 + hr * 60 + mn;
120
+ if (prev !== null && t - prev < best) best = t - prev;
121
+ prev = t;
122
+ count += 1;
123
+ }
124
+ }
125
+ }
126
+ return { best, count };
127
+ }
128
+
129
+ /** Is `tz` an IANA time zone this runtime knows? */
130
+ function isTimeZone(tz) {
131
+ try { new Intl.DateTimeFormat('en-US', { timeZone: tz }); return true; } catch { return false; }
132
+ }
133
+
134
+ /**
135
+ * Validate a recurrence. `min` is an optional floor ('15m'): the expression must never fire more often.
136
+ * @returns {string[]} problems, empty when valid
137
+ */
138
+ function validateRecurrence(recurrence, { min } = {}) {
139
+ const problems = [];
140
+ if (!recurrence || typeof recurrence !== 'object') return ['Give a schedule as { every } or { cron, timezone? }'];
141
+ const hasEvery = recurrence.every !== undefined, hasCron = recurrence.cron !== undefined;
142
+ if (hasEvery === hasCron) return ['Give exactly one of every or cron'];
143
+ if (hasEvery && parseEvery(recurrence.every) === null) problems.push(`every "${recurrence.every}" is not a whole number of minutes, hours or days (15m, 2h, 1d)`);
144
+ if (hasCron) {
145
+ const parsed = parseCron(recurrence.cron);
146
+ if (parsed.error) problems.push(parsed.error);
147
+ // EventBridge (and Quartz) cannot express "this day of month OR this weekday"; refuse it everywhere, so a
148
+ // schedule that validates here runs on every host.
149
+ else if (parsed.restricted.dom && parsed.restricted.dow) problems.push('Restrict day of month or day of week, not both');
150
+ else if (scan(parsed).count === 0) problems.push(`"${recurrence.cron}" never fires`);
151
+ }
152
+ if (recurrence.timezone !== undefined && (hasEvery || !isTimeZone(recurrence.timezone))) {
153
+ problems.push(hasEvery ? 'timezone applies to cron schedules only' : `Unknown time zone "${recurrence.timezone}"`);
154
+ }
155
+ if (!problems.length && min !== undefined) {
156
+ const floor = parseEvery(min);
157
+ const gap = minGapMinutes(recurrence);
158
+ if (floor === null) problems.push(`minimum interval "${min}" is not a duration (15m, 2h, 1d)`);
159
+ else if (gap !== null && gap < floor) problems.push(`Runs every ${gap} minute${gap === 1 ? '' : 's'} at its most frequent; the minimum is ${min}`);
160
+ }
161
+ return problems;
162
+ }
163
+
164
+ /** The comparable identity of a recurrence (what decides whether a stored schedule must be updated). */
165
+ function recurrenceKey(r) {
166
+ if (!r) return '';
167
+ return r.every !== undefined ? `every:${parseEvery(r.every)}` : `cron:${String(r.cron).trim().split(/\s+/).join(' ')}@${r.timezone || 'UTC'}`;
168
+ }
169
+
170
+ const wallClockFormats = new Map();
171
+ /**
172
+ * The wall-clock time of an instant in a time zone, as a Date whose UTC fields hold that wall clock (what `matches`
173
+ * reads). Seconds are dropped.
174
+ */
175
+ function wallClock(ms, timezone = 'UTC') {
176
+ if (timezone === 'UTC') return new Date(Math.floor(ms / 60000) * 60000);
177
+ let format = wallClockFormats.get(timezone);
178
+ if (!format) {
179
+ format = new Intl.DateTimeFormat('en-US', { timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' });
180
+ wallClockFormats.set(timezone, format);
181
+ }
182
+ const p = Object.fromEntries(format.formatToParts(new Date(ms)).map((x) => [x.type, x.value]));
183
+ return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour) % 24, Number(p.minute)));
184
+ }
185
+
186
+ /**
187
+ * The latest whole minute in (fromMs, toMs] at which a cron recurrence fires in its time zone, as epoch ms, or null.
188
+ *
189
+ * This is how one shared tick serves a calendar each installation chose: the tick asks whether the cron fired since
190
+ * the previous tick. It is stateless, so a tick that runs twice for the same slot gives the same answer (and the same
191
+ * `scheduledFor`, which is what a run dedupes on). Real instants are walked, so a wall-clock time a DST change skips
192
+ * does not fire that day, and one it repeats fires twice.
193
+ */
194
+ function lastFiringIn(recurrence, fromMs, toMs) {
195
+ const parsed = parseCron(recurrence?.cron);
196
+ if (parsed.error) return null;
197
+ const tz = recurrence.timezone || 'UTC';
198
+ for (let t = Math.floor(toMs / 60000) * 60000; t > fromMs; t -= 60000) {
199
+ if (matches(parsed, wallClock(t, tz))) return t;
200
+ }
201
+ return null;
202
+ }
203
+
204
+ module.exports = { parseEvery, parseCron, minGapMinutes, validateRecurrence, recurrenceKey, isTimeZone, matches, wallClock, lastFiringIn };
@@ -25,7 +25,7 @@ installation (Integration.config) ─┘ │
25
25
  | `steps.js`, `interpreter.js`, `transforms.js` | The step catalogue and the interpreter |
26
26
  | `validate.js` | Structure + cross-references against the manifests (steps, templates, views, settings, `$.install`) |
27
27
  | `manifests.js` | `validateManifest`: the manifests themselves (kinds, option lists, account fields) |
28
- | `compile.js` | Definition + installation → events, webhook routes, schedules, user actions |
28
+ | `compile.js` | Definition + installation → events, webhook routes, recurring triggers, user actions |
29
29
  | `runtime.js` | Ports (Api calls, link store), `runWorkflow`, `runQuery`, `renderSurface`, `runLifecycle`, `resolveOptions`, `installContext` |
30
30
  | `versioning.js` | `diff`, `checkBump`, `planUpgrade` |
31
31
  | `data-defined-integration.js` | `defineIntegrationClass`: the IntegrationBase subclass that runs it all |
@@ -96,6 +96,24 @@ different document at the same version is refused. So is a version that is not n
96
96
  semver bump smaller than the changes. Publishing goes through a conditional write, so two concurrent publishes of one
97
97
  version cannot both win. With `memoryDefinitions()` (definitions bundled in the app) the admin routes answer 501.
98
98
 
99
+ ## Schedules
100
+
101
+ A schedule-triggered workflow or a polling sync is a recurring trigger (ADR-055), the same mechanism hand-written
102
+ integrations declare as `Definition.triggers` (ADR-063 §15a). Nothing is scheduled per installation: the class
103
+ declares `instanceTriggers: { tick: '5m' }`, so devtools provisions one tick function for it, and each tick compiles
104
+ every ENABLED installation's pinned definition with its config and queues the runs that are due. Mark one
105
+ `configurable` to let installations pick their own timing, optionally with a floor:
106
+
107
+ ```json
108
+ "trigger": { "type": "schedule", "cron": "0 16 * * 1-5", "timezone": "America/New_York", "configurable": { "min": "1h" } }
109
+ "ongoing": { "mode": "poll", "every": "15m", "configurable": true }
110
+ ```
111
+
112
+ The choice goes in `workflows.<id>.schedule` / `syncs.<id>.schedule` (the configure form offers the field). An
113
+ interval runs on whole multiples of the 5-minute tick; a cron runs on the first tick after it fires. Create, update,
114
+ upgrade and delete need no scheduler call: the next tick reads the new state. A run is deduped on
115
+ `tick:<event>:<scheduledFor>`, so a redelivered run happens once.
116
+
99
117
  ## Steps (v0.1)
100
118
 
101
119
  Built-ins: `links.find`, `links.upsert`, `map`, `merge`, `template`, `set`, `stop`, `foreach` (≤1000), `branch`, `code`.
@@ -164,6 +182,4 @@ CLI as a child process; it fails, rather than skips, if `ajv` is missing. Core's
164
182
  the existing `SYNC_PAGE` pattern. `runSync` throws until then.
165
183
  - `delay` / wait steps, approvals that pause a run, and per-tenant rate limits.
166
184
  - The host renderers (the HubSpot app extension and Phone panel that draw `renderSurface` output).
167
- - Registering `compiled.schedules` as recurring schedules (Frigg's scheduler commands are one-time jobs). They compile
168
- today; nothing creates them yet.
169
185
  - Rebuilding `link:` / `idx:` rows after an identity change; `planUpgrade` reports it as `relink` / `reindex`.
@@ -2,7 +2,7 @@
2
2
  * Compile a definition + one installation into what Frigg runs: an events map shaped exactly like a hand-written
3
3
  * integration's `this.events`, plus the routing tables the runtime needs. Pure; no I/O.
4
4
  *
5
- * Only what the installation has enabled is compiled, so a disabled workflow has no event, no route and no schedule.
5
+ * Only what the installation has enabled is compiled, so a disabled workflow has no event, no route and no trigger.
6
6
  *
7
7
  * Event names: SYNC_<ID>_BACKFILL (USER_ACTION) · SYNC_<ID>_PAGE (QUEUE) · SYNC_<ID>_ONGOING (WEBHOOK|CRON)
8
8
  * WF_<ID> (WEBHOOK|CRON|USER_ACTION|QUEUE) · Q_<ID> (ROUTE) · UI_<ID> (ROUTE)
@@ -17,7 +17,7 @@ function isOn(item, chosen) {
17
17
  function compile(def, installation = {}) {
18
18
  const events = {};
19
19
  const webhooks = {}; // moduleKey -> topic -> [eventName]
20
- const schedules = []; // { event, cron, timezone }
20
+ const triggers = []; // recurring triggers (integrations/triggers.js): { name, every | cron, timezone?, configurable, choice }
21
21
  const userActions = []; // { event, label, from }
22
22
  const routes = []; // { method, path, event }
23
23
  const add = (name, e) => { events[name] = e; return name; };
@@ -39,7 +39,7 @@ function compile(def, installation = {}) {
39
39
  }
40
40
  } else if (mode === 'poll') {
41
41
  const n = add(eventName('SYNC', s.id, 'ONGOING'), { type: 'CRON', ref: { kind: 'sync', id: s.id, phase: 'ongoing' } });
42
- schedules.push({ event: n, every: s.ongoing.every || '15m' });
42
+ triggers.push({ name: n, every: s.ongoing.every || '15m', configurable: s.ongoing.configurable || false, choice: installation.syncs?.[s.id]?.schedule });
43
43
  }
44
44
  }
45
45
 
@@ -49,7 +49,10 @@ function compile(def, installation = {}) {
49
49
  const type = { webhook: 'WEBHOOK', schedule: 'CRON', userAction: 'USER_ACTION', syncRecord: 'QUEUE' }[t.type];
50
50
  const n = add(eventName('WF', w.id), { type, ...(type === 'USER_ACTION' ? { userActionType: 'DATA_ACTION', title: t.label } : {}), ref: { kind: 'workflow', id: w.id } });
51
51
  if (t.type === 'webhook') route(t.module, t.topic, n);
52
- if (t.type === 'schedule') schedules.push({ event: n, cron: t.cron, timezone: t.timezone || 'UTC' });
52
+ if (t.type === 'schedule') {
53
+ const timing = t.every !== undefined ? { every: t.every } : { cron: t.cron, ...(t.timezone ? { timezone: t.timezone } : {}) };
54
+ triggers.push({ name: n, ...timing, configurable: t.configurable || false, choice: installation.workflows?.[w.id]?.schedule });
55
+ }
53
56
  if (t.type === 'userAction') userActions.push({ event: n, label: t.label, from: t.from || null });
54
57
  if (t.type === 'syncRecord') route('$sync', `${t.sync}:${(t.on || []).join('|')}`, n);
55
58
  }
@@ -61,7 +64,7 @@ function compile(def, installation = {}) {
61
64
  routes.push({ method: 'GET', path: `/ui/${u.id}`, event: n });
62
65
  }
63
66
 
64
- return { events, webhooks, schedules, userActions, routes };
67
+ return { events, webhooks, triggers, userActions, routes };
65
68
  }
66
69
 
67
70
  /** Which compiled events a delivered webhook goes to. Topic patterns may end in ".*". */
@@ -38,6 +38,20 @@ async function settingsSchema(settings, pathPrefix, values, options, integration
38
38
  return { schema: { type: 'object', properties, ...(required.length ? { required } : {}) }, ui };
39
39
  }
40
40
 
41
+ /**
42
+ * The timing field of a schedule the definition marks configurable: an interval when its default is an interval,
43
+ * a cron (with time zone) when its default is a cron. The floor is said in the help text and enforced on save.
44
+ */
45
+ function scheduleField(recurrence, configurable) {
46
+ if (!configurable || !recurrence) return null;
47
+ const min = configurable.min ? ` No more often than every ${configurable.min}.` : '';
48
+ if (recurrence.every !== undefined) {
49
+ return { schema: { type: 'object', title: 'Schedule', properties: { every: { type: 'string', title: 'Runs every', pattern: '^\\d+\\s*(m|h|d)$', default: recurrence.every } } }, ui: { every: { 'ui:help': `Minutes, hours or days: 15m, 2h, 1d.${min}` } } };
50
+ }
51
+ return { schema: { type: 'object', title: 'Schedule', properties: { cron: { type: 'string', title: 'Cron', default: recurrence.cron }, timezone: { type: 'string', title: 'Time zone', default: recurrence.timezone || 'UTC' } } }, ui: { cron: { 'ui:help': `minute hour day-of-month month day-of-week.${min}` } } };
52
+ }
53
+ const configurableOf = (c) => (c ? (c === true ? {} : c) : false);
54
+
41
55
  const toggle = (title, description, enabledByDefault) => ({ type: 'boolean', title, ...(description ? { description } : {}), default: enabledByDefault });
42
56
  const isOn = (item, chosen) => (typeof chosen?.enabled === 'boolean' ? chosen.enabled : (item.default || 'on') === 'on');
43
57
 
@@ -63,6 +77,12 @@ async function buildConfigForm(def, config = {}, options = async () => []) {
63
77
  for (const s of def.syncs) {
64
78
  jsonSchema.properties.syncs.properties[s.id] = { type: 'object', title: s.label, properties: { enabled: toggle('On', s.description, (s.default || 'on') === 'on') } };
65
79
  data.syncs[s.id] = { enabled: isOn(s, config.syncs?.[s.id]) };
80
+ const field = s.ongoing?.mode === 'poll' && scheduleField({ every: s.ongoing.every || '15m' }, configurableOf(s.ongoing.configurable));
81
+ if (field) {
82
+ jsonSchema.properties.syncs.properties[s.id].properties.schedule = field.schema;
83
+ ((uiSchema.syncs ||= {})[s.id] ||= {}).schedule = field.ui;
84
+ if (config.syncs?.[s.id]?.schedule) data.syncs[s.id].schedule = { ...config.syncs[s.id].schedule };
85
+ }
66
86
  }
67
87
  }
68
88
 
@@ -81,6 +101,13 @@ async function buildConfigForm(def, config = {}, options = async () => []) {
81
101
  // Settings only matter while the workflow is on: required only then.
82
102
  node.dependencies = { enabled: { oneOf: [{ properties: { enabled: { const: false } } }, { properties: { enabled: { const: true } }, required: ['settings'] }] } };
83
103
  }
104
+ const t = w.trigger || {};
105
+ const field = t.type === 'schedule' && scheduleField(t.every !== undefined ? { every: t.every } : { cron: t.cron, timezone: t.timezone }, configurableOf(t.configurable));
106
+ if (field) {
107
+ node.properties.schedule = field.schema;
108
+ (uiSchema.workflows[w.id] ||= {}).schedule = field.ui;
109
+ if (chosen.schedule) data.workflows[w.id].schedule = { ...chosen.schedule };
110
+ }
84
111
  jsonSchema.properties.workflows.properties[w.id] = node;
85
112
  }
86
113
  }
@@ -21,6 +21,22 @@ const { makePorts, runWorkflow, runQuery, renderSurface, runLifecycle, resolveOp
21
21
  const { eventsIn, handshakeFor, modulesFor } = require('./webhooks');
22
22
  const { buildConfigForm, missingRequired } = require('./config-form');
23
23
 
24
+ /** The tick every data-defined trigger runs on: a chosen interval is rounded up to whole multiples of it. */
25
+ const INSTANCE_TICK = '5m';
26
+
27
+ /** A compiled definition's triggers as IntegrationBase trigger declarations: each runs its compiled event. */
28
+ function triggersOf(def, config) {
29
+ return compile(def, config).triggers.map((t) => ({
30
+ ...t,
31
+ tick: INSTANCE_TICK,
32
+ handler(payload) {
33
+ const event = this.events?.[t.name];
34
+ if (!event) throw new Error(`Trigger "${t.name}" has no compiled event in this installation`);
35
+ return event.handler({ data: { integrationId: this.id, ...payload } });
36
+ },
37
+ }));
38
+ }
39
+
24
40
  /**
25
41
  * Shape A — one class per definition id (defineIntegrationClass): the class name and modules come from the
26
42
  * definition. Publishing a new VERSION deploys nothing; a new definition ID is a new class (a deploy, and its own
@@ -80,9 +96,35 @@ function makeClass({ name, defaultId, definitions, manifests, runCode, Integrati
80
96
  let runStore = runs;
81
97
  const runRepository = () => (runStore === undefined ? (runStore = require('./repositories/workflow-run-repository').createWorkflowRunRepository()) : runStore);
82
98
  const publicBase = () => `${process.env.FRIGG_PUBLIC_URL || ''}/api/${id}-integration/webhooks`;
99
+ const pinnedDefinitions = new Map(); // `${id}@${version}` -> definition, for the trigger tick
83
100
 
84
101
  class DataDefinedIntegration extends Base {
85
- static Definition = { name, version, modules, webhooks: { enabled: true }, display }; // version is display only; installations pin their own
102
+ // version is display only; installations pin their own. instanceTriggers: schedule-triggered workflows and
103
+ // polling syncs are this class's recurring triggers, resolved per installation (triggersFor) on one 5m tick.
104
+ static Definition = { name, version, modules, webhooks: { enabled: true }, display, instanceTriggers: { tick: INSTANCE_TICK } };
105
+
106
+ /**
107
+ * The recurring triggers of one installation (ADR-055): its pinned definition compiled with its config, so a
108
+ * switched-off workflow has none and a configurable one carries the installation's choice. Each runs its
109
+ * compiled event. Read by the shared tick from the record alone (no modules, no credentials).
110
+ */
111
+ static async triggersFor({ config = {} } = {}) {
112
+ const pin = config.definition || (defaultId ? { id: defaultId } : null);
113
+ if (!pin?.id) return [];
114
+ let def;
115
+ if (pin.version) {
116
+ // Published versions are immutable, so a tick over many installations reads each one once.
117
+ const key = `${pin.id}@${pin.version}`;
118
+ if (!pinnedDefinitions.has(key)) {
119
+ if (pinnedDefinitions.size >= 100) pinnedDefinitions.clear();
120
+ pinnedDefinitions.set(key, await definitions.get(pin.id, pin.version, { checksum: pin.checksum }));
121
+ }
122
+ def = pinnedDefinitions.get(key);
123
+ } else {
124
+ def = await definitions.latest(pin.id);
125
+ }
126
+ return def ? triggersOf(def, config) : [];
127
+ }
86
128
 
87
129
  /** How the routers find data-defined classes and the store and manifests they run on. */
88
130
  static DataDefined = { definitions, manifests, shared: !defaultId, runs: () => runRepository() };
@@ -150,7 +192,10 @@ function makeClass({ name, defaultId, definitions, manifests, runCode, Integrati
150
192
  ? await definitions.get(this.def.id, msg.definitionVersion) || this.def
151
193
  : this.def;
152
194
  const installation = this.installation();
153
- if (ref.kind === 'workflow') return this.recordRun(await runWorkflow({ def, installation, workflowId: ref.id, event: msg.body ?? msg, eventId: msg.eventId, record: msg.record, ports: this.ports, manifests }));
195
+ // A trigger run may be delivered twice (a redelivery, two ticks in one slot); the trigger and the time it
196
+ // was scheduled for make its dedupe id.
197
+ const eventId = msg.eventId || (msg.trigger && msg.scheduledFor ? `tick:${msg.trigger}:${msg.scheduledFor}` : undefined);
198
+ if (ref.kind === 'workflow') return this.recordRun(await runWorkflow({ def, installation, workflowId: ref.id, event: msg.body ?? msg, eventId, record: msg.record, ports: this.ports, manifests }));
154
199
  if (ref.kind === 'query') return runQuery({ def, installation, queryId: ref.id, record: msg.record, ports: this.ports });
155
200
  if (ref.kind === 'ui') return renderSurface({ def, installation, surfaceId: ref.id, record: payload.req?.body?.record || msg.record, ports: this.ports });
156
201
  if (ref.kind === 'sync') return this.runSync(ref, msg);
@@ -252,6 +297,11 @@ function makeClass({ name, defaultId, definitions, manifests, runCode, Integrati
252
297
  return super.onDelete(params);
253
298
  }
254
299
 
300
+ /** This installation's triggers, from the definition it already loaded and its current config. */
301
+ async triggerDeclarations() {
302
+ return this.def ? triggersOf(this.def, this.config || {}) : this.constructor.triggersFor({ config: this.config || {} });
303
+ }
304
+
255
305
  /** The configure form (GET /api/integrations/:id/config/options), generated from the definition. */
256
306
  async getConfigOptions() {
257
307
  return buildConfigForm(this.def, this.config || {}, (path, values, integrationSettings) => this.optionsFor(path, values, integrationSettings));
@@ -316,11 +366,12 @@ function makeClass({ name, defaultId, definitions, manifests, runCode, Integrati
316
366
  await runLifecycle({ def: this.def, installation: this.installation(), hook: 'onUninstall', ports: this.ports });
317
367
  const next = await definitions.get(plan.config.definition.id, plan.config.definition.version);
318
368
  const out = await runLifecycle({ def: next, installation: { ...this.installation(), ...config }, hook: 'onInstall', ports: this.portsFor(next) });
319
- config = { ...config, runtime: { installed: Object.fromEntries((next.lifecycle?.onInstall || []).filter((st) => st.id).map((st) => [st.id, out.steps?.[st.id] ?? null])) } };
369
+ config = { ...config, runtime: { ...(this.config?.runtime || {}), installed: Object.fromEntries((next.lifecycle?.onInstall || []).filter((st) => st.id).map((st) => [st.id, out.steps?.[st.id] ?? null])) } };
320
370
  }
321
371
  await this.patchConfig(config);
322
372
  this.config = { ...this.config, ...config };
323
373
  await this.loadDefinition();
374
+ // Triggers need nothing here: the next tick reads the new pin and config.
324
375
  return { ...plan, config, applied: true };
325
376
  }
326
377
 
@@ -40,6 +40,9 @@
40
40
  "mapping": {
41
41
  "type": "array",
42
42
  "description": "Full replacement mapping when the customer overrides the default."
43
+ },
44
+ "schedule": {
45
+ "$ref": "#/$defs/scheduleChoice"
43
46
  }
44
47
  }
45
48
  }
@@ -54,6 +57,9 @@
54
57
  },
55
58
  "settings": {
56
59
  "type": "object"
60
+ },
61
+ "schedule": {
62
+ "$ref": "#/$defs/scheduleChoice"
57
63
  }
58
64
  }
59
65
  }
@@ -79,5 +85,46 @@
79
85
  }
80
86
  }
81
87
  }
88
+ },
89
+ "$defs": {
90
+ "scheduleChoice": {
91
+ "description": "The installation's timing for a schedule trigger or polling sync the definition marks configurable: every, or cron with an optional time zone. Honoured only within the definition's minimum; otherwise the definition's timing runs. The integration's shared trigger tick reads it (ADR-055); nothing is scheduled per installation.",
92
+ "type": "object",
93
+ "additionalProperties": false,
94
+ "properties": {
95
+ "every": {
96
+ "type": "string",
97
+ "pattern": "^\\d+\\s*(m|h|d)$"
98
+ },
99
+ "cron": {
100
+ "type": "string"
101
+ },
102
+ "timezone": {
103
+ "type": "string"
104
+ }
105
+ },
106
+ "oneOf": [
107
+ {
108
+ "required": [
109
+ "every"
110
+ ],
111
+ "not": {
112
+ "required": [
113
+ "cron"
114
+ ]
115
+ }
116
+ },
117
+ {
118
+ "required": [
119
+ "cron"
120
+ ],
121
+ "not": {
122
+ "required": [
123
+ "every"
124
+ ]
125
+ }
126
+ }
127
+ ]
128
+ }
82
129
  }
83
130
  }
@@ -217,7 +217,12 @@
217
217
  ]
218
218
  },
219
219
  "every": {
220
- "type": "string"
220
+ "type": "string",
221
+ "pattern": "^\\d+\\s*(m|h|d)$",
222
+ "description": "Poll interval (default 15m)."
223
+ },
224
+ "configurable": {
225
+ "$ref": "#/$defs/scheduleConfigurable"
221
226
  }
222
227
  }
223
228
  },
@@ -662,8 +667,7 @@
662
667
  {
663
668
  "type": "object",
664
669
  "required": [
665
- "type",
666
- "cron"
670
+ "type"
667
671
  ],
668
672
  "additionalProperties": false,
669
673
  "properties": {
@@ -671,12 +675,44 @@
671
675
  "const": "schedule"
672
676
  },
673
677
  "cron": {
674
- "type": "string"
678
+ "type": "string",
679
+ "description": "Five-field cron (minute hour day-of-month month day-of-week). Restrict day of month or day of week, not both."
675
680
  },
676
681
  "timezone": {
677
- "type": "string"
682
+ "type": "string",
683
+ "description": "IANA time zone for cron (default UTC)."
684
+ },
685
+ "every": {
686
+ "type": "string",
687
+ "pattern": "^\\d+\\s*(m|h|d)$",
688
+ "description": "Fixed interval (15m, 2h, 1d). Give cron or every."
689
+ },
690
+ "configurable": {
691
+ "$ref": "#/$defs/scheduleConfigurable"
678
692
  }
679
- }
693
+ },
694
+ "oneOf": [
695
+ {
696
+ "required": [
697
+ "cron"
698
+ ],
699
+ "not": {
700
+ "required": [
701
+ "every"
702
+ ]
703
+ }
704
+ },
705
+ {
706
+ "required": [
707
+ "every"
708
+ ],
709
+ "not": {
710
+ "required": [
711
+ "cron"
712
+ ]
713
+ }
714
+ }
715
+ ]
680
716
  },
681
717
  {
682
718
  "type": "object",
@@ -843,6 +879,24 @@
843
879
  }
844
880
  }
845
881
  ]
882
+ },
883
+ "scheduleConfigurable": {
884
+ "description": "Lets each installation choose its own timing. true: any valid timing. { min }: never more often than this (15m, 2h, 1d).",
885
+ "oneOf": [
886
+ {
887
+ "type": "boolean"
888
+ },
889
+ {
890
+ "type": "object",
891
+ "additionalProperties": false,
892
+ "properties": {
893
+ "min": {
894
+ "type": "string",
895
+ "pattern": "^\\d+\\s*(m|h|d)$"
896
+ }
897
+ }
898
+ }
899
+ ]
846
900
  }
847
901
  }
848
902
  }