@contember/engine-actions 2.2.0-alpha.15 → 2.2.0-alpha.16
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/CLAUDE.md +9 -1
- package/dist/development/index.cjs +1 -1
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +1 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/dispatch/EventDispatcher.cjs +30 -2
- package/dist/development/src/dispatch/EventDispatcher.cjs.map +1 -1
- package/dist/development/src/dispatch/EventDispatcher.js +30 -2
- package/dist/development/src/dispatch/EventDispatcher.js.map +1 -1
- package/dist/development/src/dispatch/EventsRepository.cjs +38 -2
- package/dist/development/src/dispatch/EventsRepository.cjs.map +1 -1
- package/dist/development/src/dispatch/EventsRepository.js +38 -2
- package/dist/development/src/dispatch/EventsRepository.js.map +1 -1
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs +32 -16
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/development/src/dispatch/WebhookTargetHandler.js +32 -16
- package/dist/development/src/dispatch/WebhookTargetHandler.js.map +1 -1
- package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs +6 -1
- package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs.map +1 -1
- package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js +6 -1
- package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js.map +1 -1
- package/dist/development/src/model/VariablesManager.cjs +5 -0
- package/dist/development/src/model/VariablesManager.cjs.map +1 -1
- package/dist/development/src/model/VariablesManager.js +6 -1
- package/dist/development/src/model/VariablesManager.js.map +1 -1
- package/dist/production/index.cjs +1 -1
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +1 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/dispatch/EventDispatcher.cjs +30 -2
- package/dist/production/src/dispatch/EventDispatcher.cjs.map +1 -1
- package/dist/production/src/dispatch/EventDispatcher.js +30 -2
- package/dist/production/src/dispatch/EventDispatcher.js.map +1 -1
- package/dist/production/src/dispatch/EventsRepository.cjs +38 -2
- package/dist/production/src/dispatch/EventsRepository.cjs.map +1 -1
- package/dist/production/src/dispatch/EventsRepository.js +38 -2
- package/dist/production/src/dispatch/EventsRepository.js.map +1 -1
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs +32 -16
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/production/src/dispatch/WebhookTargetHandler.js +32 -16
- package/dist/production/src/dispatch/WebhookTargetHandler.js.map +1 -1
- package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs +6 -1
- package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs.map +1 -1
- package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js +6 -1
- package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js.map +1 -1
- package/dist/production/src/model/VariablesManager.cjs +5 -0
- package/dist/production/src/model/VariablesManager.cjs.map +1 -1
- package/dist/production/src/model/VariablesManager.js +6 -1
- package/dist/production/src/model/VariablesManager.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/dispatch/EventDispatcher.d.ts.map +1 -1
- package/dist/types/dispatch/EventsRepository.d.ts +20 -1
- package/dist/types/dispatch/EventsRepository.d.ts.map +1 -1
- package/dist/types/dispatch/WebhookTargetHandler.d.ts +6 -0
- package/dist/types/dispatch/WebhookTargetHandler.d.ts.map +1 -1
- package/dist/types/graphql/resolvers/mutation/SetVariablesMutationResolver.d.ts +3 -1
- package/dist/types/graphql/resolvers/mutation/SetVariablesMutationResolver.d.ts.map +1 -1
- package/dist/types/model/VariablesManager.d.ts +2 -0
- package/dist/types/model/VariablesManager.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +17 -17
- package/src/dispatch/EventDispatcher.ts +32 -3
- package/src/dispatch/EventsRepository.ts +77 -2
- package/src/dispatch/WebhookTargetHandler.ts +41 -21
- package/src/graphql/resolvers/mutation/SetVariablesMutationResolver.ts +7 -0
- package/src/index.ts +1 -1
- package/src/model/VariablesManager.ts +6 -0
- package/tests/cases/unit/dispatchTracing.test.ts +79 -6
- package/tests/cases/unit/webhookHandler.test.ts +57 -1
package/package.json
CHANGED
|
@@ -22,27 +22,27 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@contember/authorization": "2.2.0-alpha.
|
|
26
|
-
"@contember/database": "2.2.0-alpha.
|
|
27
|
-
"@contember/database-migrations": "2.2.0-alpha.
|
|
28
|
-
"@contember/engine-common": "2.2.0-alpha.
|
|
29
|
-
"@contember/engine-content-api": "2.2.0-alpha.
|
|
30
|
-
"@contember/engine-http": "2.2.0-alpha.
|
|
31
|
-
"@contember/engine-plugins": "2.2.0-alpha.
|
|
32
|
-
"@contember/engine-system-api": "2.2.0-alpha.
|
|
33
|
-
"@contember/engine-tenant-api": "2.2.0-alpha.
|
|
34
|
-
"@contember/graphql-utils": "2.2.0-alpha.
|
|
35
|
-
"@contember/logger": "2.2.0-alpha.
|
|
36
|
-
"@contember/schema": "2.2.0-alpha.
|
|
37
|
-
"@contember/schema-utils": "2.2.0-alpha.
|
|
38
|
-
"@contember/telemetry": "2.2.0-alpha.
|
|
39
|
-
"@contember/typesafe": "2.2.0-alpha.
|
|
25
|
+
"@contember/authorization": "2.2.0-alpha.16",
|
|
26
|
+
"@contember/database": "2.2.0-alpha.16",
|
|
27
|
+
"@contember/database-migrations": "2.2.0-alpha.16",
|
|
28
|
+
"@contember/engine-common": "2.2.0-alpha.16",
|
|
29
|
+
"@contember/engine-content-api": "2.2.0-alpha.16",
|
|
30
|
+
"@contember/engine-http": "2.2.0-alpha.16",
|
|
31
|
+
"@contember/engine-plugins": "2.2.0-alpha.16",
|
|
32
|
+
"@contember/engine-system-api": "2.2.0-alpha.16",
|
|
33
|
+
"@contember/engine-tenant-api": "2.2.0-alpha.16",
|
|
34
|
+
"@contember/graphql-utils": "2.2.0-alpha.16",
|
|
35
|
+
"@contember/logger": "2.2.0-alpha.16",
|
|
36
|
+
"@contember/schema": "2.2.0-alpha.16",
|
|
37
|
+
"@contember/schema-utils": "2.2.0-alpha.16",
|
|
38
|
+
"@contember/telemetry": "2.2.0-alpha.16",
|
|
39
|
+
"@contember/typesafe": "2.2.0-alpha.16",
|
|
40
40
|
"@graphql-tools/schema": "^10.0.31",
|
|
41
41
|
"graphql-tag": "^2.12.6",
|
|
42
42
|
"prom-client": "^12.0.0"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@contember/database-tester": "2.2.0-alpha.
|
|
45
|
+
"@contember/database-tester": "2.2.0-alpha.16",
|
|
46
46
|
"@types/bun": "^1.3.10",
|
|
47
47
|
"@types/ws": "^8.18.1",
|
|
48
48
|
"graphql": "^16.13.1"
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"pg": "^8.20.0"
|
|
53
53
|
},
|
|
54
54
|
"type": "module",
|
|
55
|
-
"version": "2.2.0-alpha.
|
|
55
|
+
"version": "2.2.0-alpha.16",
|
|
56
56
|
"repository": {
|
|
57
57
|
"type": "git",
|
|
58
58
|
"url": "git+https://github.com/contember/contember.git",
|
|
@@ -4,8 +4,9 @@ import { HandledEvent } from './types.js'
|
|
|
4
4
|
import { Logger } from '@contember/logger'
|
|
5
5
|
import { ContentSchemaResolver } from '@contember/engine-http'
|
|
6
6
|
import { DatabaseContext } from '@contember/engine-system-api'
|
|
7
|
-
import { VariablesManager } from '../model/VariablesManager.js'
|
|
7
|
+
import { resolveVariable, VariablesManager } from '../model/VariablesManager.js'
|
|
8
8
|
import { Tracer } from '@contember/telemetry'
|
|
9
|
+
import { UndefinedVariableError } from './WebhookTargetHandler.js'
|
|
9
10
|
|
|
10
11
|
type ProcessBatchArgs = {
|
|
11
12
|
db: DatabaseContext
|
|
@@ -38,7 +39,7 @@ export class EventDispatcher {
|
|
|
38
39
|
async processBatch({ db, contentSchemaResolver, logger, project }: ProcessBatchArgs): Promise<ProcessBatchResult> {
|
|
39
40
|
const schema = (await contentSchemaResolver.getSchema({ db, normalize: true })).schema
|
|
40
41
|
const batchId = Math.random().toString().substring(2)
|
|
41
|
-
const batchLogger = logger.child({ loc: 'Actions.EventDispatcher', batchId })
|
|
42
|
+
const batchLogger = logger.child({ loc: 'Actions.EventDispatcher', project: project.slug, batchId })
|
|
42
43
|
const batch = await this.eventsRepository.fetchBatch(schema.actions, db.client, batchLogger)
|
|
43
44
|
if (!batch.ok) {
|
|
44
45
|
batchLogger.debug('Nothing to process', {
|
|
@@ -76,9 +77,37 @@ export class EventDispatcher {
|
|
|
76
77
|
backoffMs: 0,
|
|
77
78
|
}
|
|
78
79
|
} catch (e) {
|
|
80
|
+
if (e instanceof UndefinedVariableError) {
|
|
81
|
+
const { held, joined } = await this.eventsRepository.holdForUndefinedVariables(db.client, {
|
|
82
|
+
target: target.name,
|
|
83
|
+
batch: events.map(it => it.id),
|
|
84
|
+
variables: e.variables,
|
|
85
|
+
})
|
|
86
|
+
const message = 'Webhook target references an undefined variable, its events wait until it is set'
|
|
87
|
+
const attributes = { target: target.name, variables: e.variables, events: held }
|
|
88
|
+
// One warning per target and re-check; an event arriving meanwhile only joins the hold.
|
|
89
|
+
if (joined) {
|
|
90
|
+
batchLogger.debug(message, attributes)
|
|
91
|
+
} else {
|
|
92
|
+
batchLogger.warn(message, attributes)
|
|
93
|
+
}
|
|
94
|
+
span.setAttribute('contember.actions.held', held)
|
|
95
|
+
// setVariables may have committed after the variables were read and before the hold, when it had nothing to release yet.
|
|
96
|
+
const current = await this.variablesManager.fetchVariables(db, project.slug)
|
|
97
|
+
if (e.variables.every(name => resolveVariable(current, name) !== undefined)) {
|
|
98
|
+
await this.eventsRepository.resumeHeldForUndefinedVariables(db.client)
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
succeeded: 0,
|
|
102
|
+
retried: 0,
|
|
103
|
+
failedAfterAttempt: 0,
|
|
104
|
+
failedUnknownTarget: batch.unknownTargetFailed,
|
|
105
|
+
backoffMs: 0,
|
|
106
|
+
}
|
|
107
|
+
}
|
|
79
108
|
span.recordException(e)
|
|
80
109
|
span.setStatus('error')
|
|
81
|
-
|
|
110
|
+
batchLogger.error(e)
|
|
82
111
|
const failedEvents = events.map((it): HandledEvent => ({
|
|
83
112
|
row: it,
|
|
84
113
|
result: { ok: false, errorMessage: `Internal error` },
|
|
@@ -9,6 +9,10 @@ const ACK_TIMEOUT_MS = 1_000 * 60 * 10 // 10 minutes
|
|
|
9
9
|
const DEFAULT_REPEAT_INTERVAL_MS = 5_000 // 5 seconds
|
|
10
10
|
const DEFAULT_MAX_ATTEMPTS = 10
|
|
11
11
|
const DEFAULT_BATCH_SIZE = 1
|
|
12
|
+
/** How long a target with an undefined variable is held back before it is checked again without a variable change. */
|
|
13
|
+
const UNDEFINED_VARIABLE_RECHECK_MS = 1_000 * 60 * 10 // 10 minutes
|
|
14
|
+
/** The last log entry of an event held by {@link EventsRepository.holdForUndefinedVariables}. */
|
|
15
|
+
const heldMarkerCondition = `log -> -1 -> 'undefinedVariables' IS NOT NULL`
|
|
12
16
|
|
|
13
17
|
export class EventsRepository {
|
|
14
18
|
public async fetchBatch(actions: Actions.Schema, db: Client, logger: Logger): Promise<FetchBatchResult> {
|
|
@@ -106,7 +110,71 @@ export class EventsRepository {
|
|
|
106
110
|
})
|
|
107
111
|
}
|
|
108
112
|
|
|
109
|
-
|
|
113
|
+
/**
|
|
114
|
+
* Holds back the due events of a target that interpolates an undefined variable, the given batch included,
|
|
115
|
+
* without spending an attempt. Events arriving while the target is held join that hold, so a target is checked
|
|
116
|
+
* again once per interval and each check rewrites only what came due. {@link resumeHeldForUndefinedVariables}
|
|
117
|
+
* releases them all once variables change.
|
|
118
|
+
*/
|
|
119
|
+
public async holdForUndefinedVariables(db: Client, { target, batch, variables }: {
|
|
120
|
+
target: string
|
|
121
|
+
batch: string[]
|
|
122
|
+
variables: readonly string[]
|
|
123
|
+
}): Promise<HoldResult> {
|
|
124
|
+
const now = new Date()
|
|
125
|
+
const entry = JSON.stringify({ ok: false, errorMessage: `Undefined variable ${variables.join(', ')}`, undefinedVariables: variables })
|
|
126
|
+
return await db.transaction(async trx => {
|
|
127
|
+
const current = await SelectBuilder.create<{ visible_at: Date }>()
|
|
128
|
+
.from('actions_event')
|
|
129
|
+
.select('visible_at')
|
|
130
|
+
.where(it =>
|
|
131
|
+
it
|
|
132
|
+
.in('state', ['created', 'retrying'])
|
|
133
|
+
.compare('target', Operator.eq, target)
|
|
134
|
+
.compare('visible_at', Operator.gt, now)
|
|
135
|
+
.raw(heldMarkerCondition)
|
|
136
|
+
)
|
|
137
|
+
.orderBy('visible_at')
|
|
138
|
+
.limit(1)
|
|
139
|
+
.getResult(trx)
|
|
140
|
+
const until = current[0]?.visible_at ?? new Date(now.getTime() + UNDEFINED_VARIABLE_RECHECK_MS)
|
|
141
|
+
await this.requeue(trx, batch, until)
|
|
142
|
+
const held = await UpdateBuilder.create()
|
|
143
|
+
.table('actions_event')
|
|
144
|
+
.values<EventRow>({
|
|
145
|
+
visible_at: until,
|
|
146
|
+
// a re-check that finds the same variables missing does not grow the log
|
|
147
|
+
log: it => it.raw('CASE WHEN log -> -1 = ?::jsonb THEN log ELSE log || ?::jsonb END', entry, entry),
|
|
148
|
+
})
|
|
149
|
+
.where(it =>
|
|
150
|
+
it
|
|
151
|
+
.in('state', ['created', 'retrying'])
|
|
152
|
+
.compare('target', Operator.eq, target)
|
|
153
|
+
.or(it => it.in('id', batch).compare('visible_at', Operator.lte, now))
|
|
154
|
+
)
|
|
155
|
+
.execute(trx)
|
|
156
|
+
return { held, joined: current.length > 0 }
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Makes events held by {@link holdForUndefinedVariables} due now. Returns how many were released. */
|
|
161
|
+
public async resumeHeldForUndefinedVariables(db: Client): Promise<number> {
|
|
162
|
+
const now = new Date()
|
|
163
|
+
return await UpdateBuilder.create()
|
|
164
|
+
.table('actions_event')
|
|
165
|
+
.values<EventRow>({
|
|
166
|
+
visible_at: now,
|
|
167
|
+
})
|
|
168
|
+
.where(it =>
|
|
169
|
+
it
|
|
170
|
+
.in('state', ['created', 'retrying'])
|
|
171
|
+
.compare('visible_at', Operator.gt, now)
|
|
172
|
+
.raw(heldMarkerCondition)
|
|
173
|
+
)
|
|
174
|
+
.execute(db)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public async requeue(db: Client, events: string[], visibleAt: Date = new Date()): Promise<void> {
|
|
110
178
|
await UpdateBuilder.create()
|
|
111
179
|
.table('actions_event')
|
|
112
180
|
.values<EventRow>({
|
|
@@ -123,7 +191,7 @@ export class EventsRepository {
|
|
|
123
191
|
'retrying',
|
|
124
192
|
),
|
|
125
193
|
last_state_change: new Date(),
|
|
126
|
-
visible_at:
|
|
194
|
+
visible_at: visibleAt,
|
|
127
195
|
})
|
|
128
196
|
.where(it => it.in('id', events))
|
|
129
197
|
.execute(db)
|
|
@@ -218,6 +286,13 @@ export type FetchBatchResult =
|
|
|
218
286
|
| { ok: true; events: EventRow[]; target: Actions.AnyTarget; unknownTargetFailed: number }
|
|
219
287
|
| { ok: false; backoffMs?: number; unknownTargetFailed: number }
|
|
220
288
|
|
|
289
|
+
export type HoldResult = {
|
|
290
|
+
/** Events held by this call. */
|
|
291
|
+
held: number
|
|
292
|
+
/** The target was already held, these events joined that hold. */
|
|
293
|
+
joined: boolean
|
|
294
|
+
}
|
|
295
|
+
|
|
221
296
|
export type PersistProcessedResult = {
|
|
222
297
|
/** Events delivered successfully (terminal). */
|
|
223
298
|
succeeded: number
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Actions, ActionsPayload } from '@contember/schema'
|
|
2
2
|
import { EventRow, HandledEvent, InvokeHandler, InvokeHandlerArgs } from './types.js'
|
|
3
|
-
import { VariablesMap } from '../model/VariablesManager.js'
|
|
3
|
+
import { resolveVariable, VariablesMap } from '../model/VariablesManager.js'
|
|
4
4
|
import * as Typesafe from '@contember/typesafe'
|
|
5
5
|
import { FetcherResponse, WebhookFetcher } from './WebhookFetcher.js'
|
|
6
6
|
import { Logger } from '@contember/logger'
|
|
7
7
|
import { formatTraceparent, INVALID_TRACE_ID, Tracer } from '@contember/telemetry'
|
|
8
|
+
import { replaceActionsVariables } from '@contember/schema-utils'
|
|
8
9
|
|
|
9
10
|
const DEFAULT_TIMEOUT_MS = 30_000 // 30 seconds
|
|
10
11
|
|
|
@@ -52,6 +53,18 @@ class WebhookRequestError extends Error {
|
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
55
|
|
|
56
|
+
/** The target interpolates a variable that has no value, so no request was made. */
|
|
57
|
+
export class UndefinedVariableError extends Error {
|
|
58
|
+
constructor(public readonly variables: readonly string[]) {
|
|
59
|
+
super(`Undefined variable ${variables.join(', ')}`)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type ResolvedRequest = {
|
|
64
|
+
url: string
|
|
65
|
+
headers: Record<string, string>
|
|
66
|
+
}
|
|
67
|
+
|
|
55
68
|
export type WebhookTargetHandlerOptions = {
|
|
56
69
|
propagateToWebhooks: boolean
|
|
57
70
|
}
|
|
@@ -66,6 +79,8 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
66
79
|
|
|
67
80
|
public async handle({ target, events, logger, variables }: InvokeHandlerArgs<Actions.WebhookTarget>): Promise<HandledEvent[]> {
|
|
68
81
|
const timeoutMs = target.timeoutMs
|
|
82
|
+
// Outside the try below: an undefined variable is no failed delivery, the dispatcher holds the target back instead.
|
|
83
|
+
const request = this.resolveVariables(target, variables)
|
|
69
84
|
|
|
70
85
|
const start = process.hrtime.bigint()
|
|
71
86
|
const getDuration = () => Math.floor(Number((process.hrtime.bigint() - start) / BigInt(1_000_000)))
|
|
@@ -82,7 +97,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
82
97
|
})
|
|
83
98
|
const response = await this.tracer.withSpan(span, async () => {
|
|
84
99
|
try {
|
|
85
|
-
const response = await this.fetch(timeoutMs ?? DEFAULT_TIMEOUT_MS, target,
|
|
100
|
+
const response = await this.fetch(timeoutMs ?? DEFAULT_TIMEOUT_MS, target, request, events)
|
|
86
101
|
span.setAttribute('http.response.status_code', response.status)
|
|
87
102
|
if (!response.ok) {
|
|
88
103
|
span.setStatus('error')
|
|
@@ -227,30 +242,24 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
227
242
|
return errorMessages
|
|
228
243
|
}
|
|
229
244
|
|
|
230
|
-
private async fetch(timeoutMs: number, target: Actions.WebhookTarget,
|
|
245
|
+
private async fetch(timeoutMs: number, target: Actions.WebhookTarget, request: ResolvedRequest, events: EventRow[]): Promise<FetcherResponse> {
|
|
231
246
|
return await withTimeout(timeoutMs, async abortController => {
|
|
232
|
-
return await this.doFetch(target,
|
|
247
|
+
return await this.doFetch(target, request, abortController, events)
|
|
233
248
|
})
|
|
234
249
|
}
|
|
235
250
|
|
|
236
251
|
private async doFetch(
|
|
237
252
|
target: Actions.WebhookTarget,
|
|
238
|
-
|
|
253
|
+
request: ResolvedRequest,
|
|
239
254
|
abortController: AbortController,
|
|
240
255
|
events: EventRow[],
|
|
241
256
|
): Promise<FetcherResponse> {
|
|
242
|
-
|
|
243
|
-
const resolvedHeaders = Object.fromEntries(
|
|
244
|
-
Object.entries(target.headers ?? {})
|
|
245
|
-
.map(([key, value]) => [key, this.resolveVariables(value, variables)]),
|
|
246
|
-
)
|
|
247
|
-
|
|
248
|
-
return await this.fetcher.fetch(resolvedUrl, {
|
|
257
|
+
return await this.fetcher.fetch(request.url, {
|
|
249
258
|
method: 'POST',
|
|
250
259
|
headers: {
|
|
251
260
|
['User-Agent']: 'Contember Actions',
|
|
252
|
-
...this.createTraceHeaders(
|
|
253
|
-
...
|
|
261
|
+
...this.createTraceHeaders(request.headers),
|
|
262
|
+
...request.headers,
|
|
254
263
|
['Content-type']: 'application/json',
|
|
255
264
|
},
|
|
256
265
|
signal: abortController.signal,
|
|
@@ -308,13 +317,24 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
308
317
|
}
|
|
309
318
|
}
|
|
310
319
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
320
|
+
/** Throws {@link UndefinedVariableError} naming every variable without a value, an empty one included. */
|
|
321
|
+
private resolveVariables(target: Actions.WebhookTarget, variables: VariablesMap): ResolvedRequest {
|
|
322
|
+
const undefinedVariables = new Set<string>()
|
|
323
|
+
const resolve = (subject: string) =>
|
|
324
|
+
replaceActionsVariables(subject, name => {
|
|
325
|
+
const value = resolveVariable(variables, name)
|
|
326
|
+
if (value === undefined) {
|
|
327
|
+
undefinedVariables.add(name)
|
|
328
|
+
return ''
|
|
329
|
+
}
|
|
330
|
+
return value
|
|
331
|
+
})
|
|
332
|
+
const url = resolve(target.url)
|
|
333
|
+
const headers = Object.fromEntries(Object.entries(target.headers ?? {}).map(([key, value]) => [key, resolve(value)]))
|
|
334
|
+
if (undefinedVariables.size > 0) {
|
|
335
|
+
throw new UndefinedVariableError([...undefinedVariables])
|
|
336
|
+
}
|
|
337
|
+
return { url, headers }
|
|
318
338
|
}
|
|
319
339
|
}
|
|
320
340
|
|
|
@@ -2,10 +2,13 @@ import { MutationResolvers, MutationSetVariablesArgs } from '../../schema/index.
|
|
|
2
2
|
import { ActionsContext } from '../ActionsContext.js'
|
|
3
3
|
import { VariablesManager } from '../../../model/VariablesManager.js'
|
|
4
4
|
import { ActionsAuthorizationActions } from '../../../authorization/index.js'
|
|
5
|
+
import { EventsRepository } from '../../../dispatch/EventsRepository.js'
|
|
6
|
+
import { notify } from '../../../utils/notifyChannel.js'
|
|
5
7
|
|
|
6
8
|
export class SetVariablesMutationResolver implements MutationResolvers<ActionsContext> {
|
|
7
9
|
constructor(
|
|
8
10
|
private readonly variablesManager: VariablesManager,
|
|
11
|
+
private readonly eventsRepository: EventsRepository,
|
|
9
12
|
) {
|
|
10
13
|
}
|
|
11
14
|
|
|
@@ -13,6 +16,10 @@ export class SetVariablesMutationResolver implements MutationResolvers<ActionsCo
|
|
|
13
16
|
await ctx.requireAccess(ActionsAuthorizationActions.VARIABLES_SET)
|
|
14
17
|
|
|
15
18
|
await this.variablesManager.setVariables(ctx.db, args, ctx.project.slug)
|
|
19
|
+
// After the variables are committed, so the worker re-checks held events against the new values.
|
|
20
|
+
if (await this.eventsRepository.resumeHeldForUndefinedVariables(ctx.db.client) > 0) {
|
|
21
|
+
await notify(ctx.db.client, ctx.project.slug)
|
|
22
|
+
}
|
|
16
23
|
|
|
17
24
|
return {
|
|
18
25
|
ok: true,
|
package/src/index.ts
CHANGED
|
@@ -107,7 +107,7 @@ export default class ActionsPlugin implements Plugin {
|
|
|
107
107
|
const eventsQueryResolver = new EventsQueryResolver()
|
|
108
108
|
const processBatchMutationResolver = new ProcessBatchMutationResolver(actions_eventDispatcher)
|
|
109
109
|
const variablesQueryResolver = new VariablesQueryResolver(actions_variableManager)
|
|
110
|
-
const setVariablesMutationResolver = new SetVariablesMutationResolver(actions_variableManager)
|
|
110
|
+
const setVariablesMutationResolver = new SetVariablesMutationResolver(actions_variableManager, actions_eventRepository)
|
|
111
111
|
const resolversFactory = new ResolversFactory(
|
|
112
112
|
eventsQueryResolver,
|
|
113
113
|
processBatchMutationResolver,
|
|
@@ -8,6 +8,12 @@ import { UserInputError } from '@contember/graphql-utils'
|
|
|
8
8
|
|
|
9
9
|
export type VariablesMap = Record<string, string>
|
|
10
10
|
|
|
11
|
+
/** A variable's value for interpolation; an empty value counts as unset, and only own entries count at all. */
|
|
12
|
+
export const resolveVariable = (variables: VariablesMap, name: string): string | undefined => {
|
|
13
|
+
const value = Object.hasOwn(variables, name) ? variables[name] : ''
|
|
14
|
+
return value === '' ? undefined : value
|
|
15
|
+
}
|
|
16
|
+
|
|
11
17
|
/** Between the project (or DEFAULT) prefix and the variable name: `MY_PROJECT_ACTIONS_VARIABLE_API_KEY`. */
|
|
12
18
|
const ENV_NAME_INFIX = '_ACTIONS_VARIABLE_'
|
|
13
19
|
|
|
@@ -7,11 +7,11 @@ import { Actions } from '@contember/schema'
|
|
|
7
7
|
import { emptySchema } from '@contember/schema-utils'
|
|
8
8
|
import { noopTracer, ReadableSpan } from '@contember/telemetry'
|
|
9
9
|
import { EventDispatcher } from '../../../src/dispatch/EventDispatcher.js'
|
|
10
|
-
import { EventsRepository, FetchBatchResult, PersistProcessedResult } from '../../../src/dispatch/EventsRepository.js'
|
|
10
|
+
import { EventsRepository, FetchBatchResult, HoldResult, PersistProcessedResult } from '../../../src/dispatch/EventsRepository.js'
|
|
11
11
|
import { TargetHandlerResolver } from '../../../src/dispatch/TargetHandlerResolver.js'
|
|
12
12
|
import { HandledEvent, InvokeHandler, InvokeHandlerArgs } from '../../../src/dispatch/types.js'
|
|
13
13
|
import { FetcherResponse, WebhookFetcher } from '../../../src/dispatch/WebhookFetcher.js'
|
|
14
|
-
import { WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
|
|
14
|
+
import { UndefinedVariableError, WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
|
|
15
15
|
import { VariablesManager, VariablesMap } from '../../../src/model/VariablesManager.js'
|
|
16
16
|
import { createTestEvent } from '../../src/event.js'
|
|
17
17
|
import { createRecordingTracer } from '../../src/tracer.js'
|
|
@@ -31,10 +31,13 @@ const idleBatch: FetchBatchResult = { ok: false, backoffMs: 100, unknownTargetFa
|
|
|
31
31
|
|
|
32
32
|
class StubEventsRepository extends EventsRepository {
|
|
33
33
|
public readonly persisted: HandledEvent[][] = []
|
|
34
|
+
public readonly held: Parameters<EventsRepository['holdForUndefinedVariables']>[1][] = []
|
|
35
|
+
public resumed = 0
|
|
34
36
|
|
|
35
37
|
constructor(
|
|
36
38
|
private readonly batch: FetchBatchResult,
|
|
37
39
|
private readonly result: PersistProcessedResult,
|
|
40
|
+
private readonly holdResult: HoldResult = { held: 5, joined: false },
|
|
38
41
|
) {
|
|
39
42
|
super()
|
|
40
43
|
}
|
|
@@ -47,15 +50,26 @@ class StubEventsRepository extends EventsRepository {
|
|
|
47
50
|
this.persisted.push(handled)
|
|
48
51
|
return this.result
|
|
49
52
|
}
|
|
53
|
+
|
|
54
|
+
override async holdForUndefinedVariables(db: Client, args: Parameters<EventsRepository['holdForUndefinedVariables']>[1]): Promise<HoldResult> {
|
|
55
|
+
this.held.push(args)
|
|
56
|
+
return this.holdResult
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
override async resumeHeldForUndefinedVariables(): Promise<number> {
|
|
60
|
+
this.resumed++
|
|
61
|
+
return 1
|
|
62
|
+
}
|
|
50
63
|
}
|
|
51
64
|
|
|
52
65
|
class StubVariablesManager extends VariablesManager {
|
|
53
|
-
constructor() {
|
|
66
|
+
constructor(private readonly variables: VariablesMap[] = [{}]) {
|
|
54
67
|
super({})
|
|
55
68
|
}
|
|
56
69
|
|
|
70
|
+
/** Answers with the given maps in turn, the last one from then on. */
|
|
57
71
|
override async fetchVariables(): Promise<VariablesMap> {
|
|
58
|
-
return {}
|
|
72
|
+
return (this.variables.length > 1 ? this.variables.shift() : this.variables[0]) ?? {}
|
|
59
73
|
}
|
|
60
74
|
}
|
|
61
75
|
|
|
@@ -106,11 +120,11 @@ const contentSchemaResolver = createMock<ContentSchemaResolver>({
|
|
|
106
120
|
getSchema: async () => ({ schema: emptySchema, meta: {} }),
|
|
107
121
|
})
|
|
108
122
|
|
|
109
|
-
const processBatch = async (dispatcher: EventDispatcher) =>
|
|
123
|
+
const processBatch = async (dispatcher: EventDispatcher, loggerHandler = new TestLoggerHandler()) =>
|
|
110
124
|
await dispatcher.processBatch({
|
|
111
125
|
db: createDatabaseContext(),
|
|
112
126
|
contentSchemaResolver,
|
|
113
|
-
logger: createLogger(
|
|
127
|
+
logger: createLogger(loggerHandler),
|
|
114
128
|
project: { slug: 'blog' },
|
|
115
129
|
})
|
|
116
130
|
|
|
@@ -202,3 +216,62 @@ test('dispatch: the webhook span nests under the dispatch span', async () => {
|
|
|
202
216
|
expect(webhookSpan?.context.traceId).toBe(dispatchSpan.context.traceId)
|
|
203
217
|
expect(requests[0].get('traceparent')).toContain(dispatchSpan.context.traceId)
|
|
204
218
|
})
|
|
219
|
+
|
|
220
|
+
test('dispatch: an undefined variable holds the whole target back with one warning and no spent attempt', async () => {
|
|
221
|
+
const { exporter, tracer, flush } = createRecordingTracer()
|
|
222
|
+
const loggerHandler = new TestLoggerHandler()
|
|
223
|
+
const repository = new StubEventsRepository(okBatch, { succeeded: 0, retried: 0, failed: 0 })
|
|
224
|
+
const resolver = new StubTargetHandlerResolver(async () => {
|
|
225
|
+
throw new UndefinedVariableError(['TOKEN'])
|
|
226
|
+
})
|
|
227
|
+
const dispatcher = new EventDispatcher(repository, new StubVariablesManager(), resolver, tracer)
|
|
228
|
+
|
|
229
|
+
const result = await processBatch(dispatcher, loggerHandler)
|
|
230
|
+
await flush()
|
|
231
|
+
|
|
232
|
+
expect(result).toStrictEqual({ succeeded: 0, retried: 0, failedAfterAttempt: 0, failedUnknownTarget: 0, backoffMs: 0 })
|
|
233
|
+
expect(repository.persisted).toStrictEqual([])
|
|
234
|
+
expect(repository.held).toStrictEqual([{ target: 'test_target', batch: events.map(it => it.id), variables: ['TOKEN'] }])
|
|
235
|
+
const reported = loggerHandler.messages.filter(it => it.level.name !== 'debug')
|
|
236
|
+
expect(reported).toHaveLength(1)
|
|
237
|
+
const [warning] = reported
|
|
238
|
+
expect(warning.level.name).toBe('warn')
|
|
239
|
+
expect(warning.message).toBe('Webhook target references an undefined variable, its events wait until it is set')
|
|
240
|
+
expect(warning.loggerAttributes.project).toBe('blog')
|
|
241
|
+
// exact match: the variable names only, never a value
|
|
242
|
+
expect(warning.ownAttributes).toStrictEqual({ target: 'test_target', variables: ['TOKEN'], events: 5 })
|
|
243
|
+
const span = dispatchSpanOf(exporter.spans)
|
|
244
|
+
expect(span.status.code).toBe('unset')
|
|
245
|
+
expect(span.attributes['contember.actions.held']).toBe(5)
|
|
246
|
+
expect(repository.resumed).toBe(0)
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
const undefinedTokenResolver = () =>
|
|
250
|
+
new StubTargetHandlerResolver(async () => {
|
|
251
|
+
throw new UndefinedVariableError(['TOKEN'])
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
test('dispatch: an event joining a held target is logged at debug level only', async () => {
|
|
255
|
+
const loggerHandler = new TestLoggerHandler()
|
|
256
|
+
const repository = new StubEventsRepository(okBatch, { succeeded: 0, retried: 0, failed: 0 }, { held: 1, joined: true })
|
|
257
|
+
const dispatcher = new EventDispatcher(repository, new StubVariablesManager(), undefinedTokenResolver(), createRecordingTracer().tracer)
|
|
258
|
+
|
|
259
|
+
await processBatch(dispatcher, loggerHandler)
|
|
260
|
+
|
|
261
|
+
expect(repository.held).toHaveLength(1)
|
|
262
|
+
expect(loggerHandler.messages.filter(it => it.level.name !== 'debug')).toStrictEqual([])
|
|
263
|
+
const joined = loggerHandler.messages.find(it => it.message === 'Webhook target references an undefined variable, its events wait until it is set')
|
|
264
|
+
expect(joined?.ownAttributes).toStrictEqual({ target: 'test_target', variables: ['TOKEN'], events: 1 })
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
test('dispatch: a variable set while the batch was being held releases the hold at once', async () => {
|
|
268
|
+
const repository = new StubEventsRepository(okBatch, { succeeded: 0, retried: 0, failed: 0 })
|
|
269
|
+
// read once for the request, then again after the hold, by when setVariables has committed
|
|
270
|
+
const variablesManager = new StubVariablesManager([{}, { TOKEN: 'secret' }])
|
|
271
|
+
const dispatcher = new EventDispatcher(repository, variablesManager, undefinedTokenResolver(), createRecordingTracer().tracer)
|
|
272
|
+
|
|
273
|
+
await processBatch(dispatcher)
|
|
274
|
+
|
|
275
|
+
expect(repository.held).toHaveLength(1)
|
|
276
|
+
expect(repository.resumed).toBe(1)
|
|
277
|
+
})
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, test } from 'bun:test'
|
|
2
|
-
import { WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
|
|
2
|
+
import { UndefinedVariableError, WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
|
|
3
3
|
import { FetcherResponse, WebhookFetcher } from '../../../src/dispatch/WebhookFetcher.js'
|
|
4
4
|
import { noopTracer } from '@contember/telemetry'
|
|
5
5
|
import { createLogger, Logger, TestLoggerHandler } from '@contember/logger'
|
|
@@ -140,6 +140,62 @@ describe('webhook request', () => {
|
|
|
140
140
|
assert.equal(fetchCalled, true)
|
|
141
141
|
})
|
|
142
142
|
})
|
|
143
|
+
describe('webhook variables', () => {
|
|
144
|
+
const target: Actions.WebhookTarget = {
|
|
145
|
+
name: 'test_target',
|
|
146
|
+
type: 'webhook',
|
|
147
|
+
url: 'http://{{HOST}}/{{PATH}}',
|
|
148
|
+
headers: { Authorization: 'Bearer {{TOKEN}}', 'X-Path': '{{PATH}}' },
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
test('interpolates variables into the URL and headers', async () => {
|
|
152
|
+
const requests: { url: string; headers: Headers }[] = []
|
|
153
|
+
const webhookHandler = createHandler({
|
|
154
|
+
fetch(url: string, init: RequestInit): Promise<FetcherResponse> {
|
|
155
|
+
requests.push({ url, headers: new Headers(init.headers) })
|
|
156
|
+
return okResponse
|
|
157
|
+
},
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
await webhookHandler.handle({
|
|
161
|
+
logger: createLogger(new TestLoggerHandler()),
|
|
162
|
+
target,
|
|
163
|
+
events: [createTestEvent(0)],
|
|
164
|
+
variables: { HOST: 'example.com', PATH: 'hook', TOKEN: 'secret' },
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
assert.equal(requests.length, 1)
|
|
168
|
+
assert.equal(requests[0].url, 'http://example.com/hook')
|
|
169
|
+
assert.equal(requests[0].headers.get('Authorization'), 'Bearer secret')
|
|
170
|
+
assert.equal(requests[0].headers.get('X-Path'), 'hook')
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
test('throws a typed error naming every undefined variable before any request', async () => {
|
|
174
|
+
const testLoggerHandler = new TestLoggerHandler()
|
|
175
|
+
let fetchCalled = false
|
|
176
|
+
const webhookHandler = createHandler({
|
|
177
|
+
fetch(): Promise<FetcherResponse> {
|
|
178
|
+
fetchCalled = true
|
|
179
|
+
return okResponse
|
|
180
|
+
},
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
const error = await webhookHandler.handle({
|
|
184
|
+
logger: createLogger(testLoggerHandler),
|
|
185
|
+
target: { ...target, url: 'http://{{HOST}}/{{constructor}}/{{PATH}}' },
|
|
186
|
+
events: [createTestEvent(0)],
|
|
187
|
+
// an empty value counts as undefined, and so does a name an object inherits
|
|
188
|
+
variables: { HOST: 'example.com', PATH: '' },
|
|
189
|
+
}).then(() => null, (e: unknown) => e)
|
|
190
|
+
|
|
191
|
+
expect(error).toBeInstanceOf(UndefinedVariableError)
|
|
192
|
+
expect(error instanceof UndefinedVariableError ? error.variables : null).toStrictEqual(['constructor', 'PATH', 'TOKEN'])
|
|
193
|
+
assert.equal(fetchCalled, false)
|
|
194
|
+
// the dispatcher reports it once for the whole target, the handler stays quiet
|
|
195
|
+
assert.deepStrictEqual(testLoggerHandler.messages, [])
|
|
196
|
+
})
|
|
197
|
+
})
|
|
198
|
+
|
|
143
199
|
describe('webhook response', () => {
|
|
144
200
|
test('successful response', async () => {
|
|
145
201
|
const testLoggerHandler = new TestLoggerHandler()
|