@webiny/api-apw 0.0.0-unstable.d7f521b032 → 0.0.0-unstable.ecd8734205
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/package.json +31 -31
- package/scheduler/handlers/executeAction/index.d.ts +1 -1
- package/scheduler/handlers/executeAction/index.js +21 -4
- package/scheduler/handlers/executeAction/index.js.map +1 -1
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js +2 -0
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js.map +1 -1
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@webiny/api-apw",
|
3
|
-
"version": "0.0.0-unstable.
|
3
|
+
"version": "0.0.0-unstable.ecd8734205",
|
4
4
|
"keywords": [
|
5
5
|
"apw:base"
|
6
6
|
],
|
@@ -17,27 +17,27 @@
|
|
17
17
|
"@aws-sdk/client-cloudwatch-events": "3.54.1",
|
18
18
|
"@babel/runtime": "7.20.13",
|
19
19
|
"@commodo/fields": "1.1.2-beta.20",
|
20
|
-
"@webiny/api": "0.0.0-unstable.
|
21
|
-
"@webiny/api-admin-settings": "0.0.0-unstable.
|
22
|
-
"@webiny/api-headless-cms": "0.0.0-unstable.
|
23
|
-
"@webiny/api-i18n": "0.0.0-unstable.
|
24
|
-
"@webiny/api-i18n-ddb": "0.0.0-unstable.
|
25
|
-
"@webiny/api-mailer": "0.0.0-unstable.
|
26
|
-
"@webiny/api-page-builder": "0.0.0-unstable.
|
27
|
-
"@webiny/api-security": "0.0.0-unstable.
|
28
|
-
"@webiny/api-tenancy": "0.0.0-unstable.
|
29
|
-
"@webiny/api-wcp": "0.0.0-unstable.
|
30
|
-
"@webiny/db-dynamodb": "0.0.0-unstable.
|
31
|
-
"@webiny/error": "0.0.0-unstable.
|
32
|
-
"@webiny/handler": "0.0.0-unstable.
|
33
|
-
"@webiny/handler-client": "0.0.0-unstable.
|
34
|
-
"@webiny/handler-db": "0.0.0-unstable.
|
35
|
-
"@webiny/handler-graphql": "0.0.0-unstable.
|
36
|
-
"@webiny/handler-logs": "0.0.0-unstable.
|
37
|
-
"@webiny/plugins": "0.0.0-unstable.
|
38
|
-
"@webiny/pubsub": "0.0.0-unstable.
|
39
|
-
"@webiny/utils": "0.0.0-unstable.
|
40
|
-
"@webiny/validation": "0.0.0-unstable.
|
20
|
+
"@webiny/api": "0.0.0-unstable.ecd8734205",
|
21
|
+
"@webiny/api-admin-settings": "0.0.0-unstable.ecd8734205",
|
22
|
+
"@webiny/api-headless-cms": "0.0.0-unstable.ecd8734205",
|
23
|
+
"@webiny/api-i18n": "0.0.0-unstable.ecd8734205",
|
24
|
+
"@webiny/api-i18n-ddb": "0.0.0-unstable.ecd8734205",
|
25
|
+
"@webiny/api-mailer": "0.0.0-unstable.ecd8734205",
|
26
|
+
"@webiny/api-page-builder": "0.0.0-unstable.ecd8734205",
|
27
|
+
"@webiny/api-security": "0.0.0-unstable.ecd8734205",
|
28
|
+
"@webiny/api-tenancy": "0.0.0-unstable.ecd8734205",
|
29
|
+
"@webiny/api-wcp": "0.0.0-unstable.ecd8734205",
|
30
|
+
"@webiny/db-dynamodb": "0.0.0-unstable.ecd8734205",
|
31
|
+
"@webiny/error": "0.0.0-unstable.ecd8734205",
|
32
|
+
"@webiny/handler": "0.0.0-unstable.ecd8734205",
|
33
|
+
"@webiny/handler-client": "0.0.0-unstable.ecd8734205",
|
34
|
+
"@webiny/handler-db": "0.0.0-unstable.ecd8734205",
|
35
|
+
"@webiny/handler-graphql": "0.0.0-unstable.ecd8734205",
|
36
|
+
"@webiny/handler-logs": "0.0.0-unstable.ecd8734205",
|
37
|
+
"@webiny/plugins": "0.0.0-unstable.ecd8734205",
|
38
|
+
"@webiny/pubsub": "0.0.0-unstable.ecd8734205",
|
39
|
+
"@webiny/utils": "0.0.0-unstable.ecd8734205",
|
40
|
+
"@webiny/validation": "0.0.0-unstable.ecd8734205",
|
41
41
|
"dayjs": "1.11.7",
|
42
42
|
"lodash": "4.17.21",
|
43
43
|
"mdbid": "1.0.0"
|
@@ -46,14 +46,14 @@
|
|
46
46
|
"@babel/cli": "^7.19.3",
|
47
47
|
"@babel/core": "^7.19.3",
|
48
48
|
"@babel/preset-env": "^7.19.4",
|
49
|
-
"@webiny/api-headless-cms-ddb": "^0.0.0-unstable.
|
50
|
-
"@webiny/api-page-builder-so-ddb": "^0.0.0-unstable.
|
51
|
-
"@webiny/api-security-so-ddb": "^0.0.0-unstable.
|
52
|
-
"@webiny/api-tenancy-so-ddb": "^0.0.0-unstable.
|
53
|
-
"@webiny/cli": "^0.0.0-unstable.
|
54
|
-
"@webiny/handler-aws": "^0.0.0-unstable.
|
55
|
-
"@webiny/project-utils": "^0.0.0-unstable.
|
56
|
-
"@webiny/wcp": "^0.0.0-unstable.
|
49
|
+
"@webiny/api-headless-cms-ddb": "^0.0.0-unstable.ecd8734205",
|
50
|
+
"@webiny/api-page-builder-so-ddb": "^0.0.0-unstable.ecd8734205",
|
51
|
+
"@webiny/api-security-so-ddb": "^0.0.0-unstable.ecd8734205",
|
52
|
+
"@webiny/api-tenancy-so-ddb": "^0.0.0-unstable.ecd8734205",
|
53
|
+
"@webiny/cli": "^0.0.0-unstable.ecd8734205",
|
54
|
+
"@webiny/handler-aws": "^0.0.0-unstable.ecd8734205",
|
55
|
+
"@webiny/project-utils": "^0.0.0-unstable.ecd8734205",
|
56
|
+
"@webiny/wcp": "^0.0.0-unstable.ecd8734205",
|
57
57
|
"get-yarn-workspaces": "^1.0.2",
|
58
58
|
"graphql": "^15.7.2",
|
59
59
|
"jest": "^28.1.0",
|
@@ -72,5 +72,5 @@
|
|
72
72
|
"build": "yarn webiny run build",
|
73
73
|
"watch": "yarn webiny run watch"
|
74
74
|
},
|
75
|
-
"gitHead": "
|
75
|
+
"gitHead": "ecd8734205e0e21ae04076c28ff9806dad07a730"
|
76
76
|
}
|
@@ -9,5 +9,5 @@ export interface HandlerArgs {
|
|
9
9
|
interface Configuration {
|
10
10
|
storageOperations: ApwScheduleActionStorageOperations;
|
11
11
|
}
|
12
|
-
export declare const executeActionHandlerPlugins: (config: Configuration) => ((import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[] | import("@webiny/handler").
|
12
|
+
export declare const executeActionHandlerPlugins: (config: Configuration) => ((import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[] | import("@webiny/handler-aws").RawEventHandler<HandlerArgs, import("@webiny/handler/types").Context, any> | ContextPlugin<import("@webiny/api/types").Context>)[];
|
13
13
|
export {};
|
@@ -9,7 +9,7 @@ var _api = require("@webiny/api");
|
|
9
9
|
var _PageBuilderGraphQL = require("./plugins/PageBuilderGraphQL");
|
10
10
|
var _HeadlessCMSGraphQL = require("./plugins/HeadlessCMSGraphQL");
|
11
11
|
var _ApplicationGraphQL = require("./plugins/ApplicationGraphQL");
|
12
|
-
var
|
12
|
+
var _handlerAws = require("@webiny/handler-aws");
|
13
13
|
/**
|
14
14
|
* Handler that execute the provided action(s) for the schedule action workflow.
|
15
15
|
*/
|
@@ -17,7 +17,7 @@ const createExecuteActionLambda = params => {
|
|
17
17
|
const {
|
18
18
|
storageOperations
|
19
19
|
} = params;
|
20
|
-
return (0,
|
20
|
+
return (0, _handlerAws.createRawEventHandler)(async ({
|
21
21
|
payload,
|
22
22
|
context
|
23
23
|
}) => {
|
@@ -111,7 +111,7 @@ const createExecuteActionLambda = params => {
|
|
111
111
|
console.log(JSON.stringify(item));
|
112
112
|
continue;
|
113
113
|
}
|
114
|
-
|
114
|
+
console.log(`Invoking Lambda "${name}" with url "${url}".`);
|
115
115
|
// Perform the actual action call.
|
116
116
|
const response = await context.handlerClient.invoke({
|
117
117
|
name,
|
@@ -132,9 +132,26 @@ const createExecuteActionLambda = params => {
|
|
132
132
|
},
|
133
133
|
await: true
|
134
134
|
});
|
135
|
+
/**
|
136
|
+
*
|
137
|
+
*/
|
138
|
+
await storageOperations.delete({
|
139
|
+
locale,
|
140
|
+
tenant,
|
141
|
+
id: item.id
|
142
|
+
});
|
143
|
+
/**
|
144
|
+
* Check for the response and log the error if any.
|
145
|
+
*/
|
135
146
|
if (response !== null && response !== void 0 && response.body) {
|
147
|
+
var _response$body$data, _response$body$data$c;
|
148
|
+
const error = (_response$body$data = response.body.data) === null || _response$body$data === void 0 ? void 0 : (_response$body$data$c = _response$body$data.content) === null || _response$body$data$c === void 0 ? void 0 : _response$body$data$c.error;
|
149
|
+
if (!error) {
|
150
|
+
console.log("Invoke successful.");
|
151
|
+
continue;
|
152
|
+
}
|
136
153
|
console.log(JSON.stringify({
|
137
|
-
|
154
|
+
error
|
138
155
|
}, null, 2));
|
139
156
|
continue;
|
140
157
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["createExecuteActionLambda","params","storageOperations","createEvent","payload","context","log","console","applicationGraphQLPlugins","plugins","byType","ApplicationGraphQL","type","length","error","applicationGraphQLPluginCache","getApplicationGraphQLPlugin","data","plugin","canUse","apwSettings","getApwSettings","futureDatetime","datetime","locale","tenant","items","list","where","datetime_startsWith","getIsoStringTillMinutes","sort","limit","item","action","JSON","stringify","name","getArn","settings","url","getUrl","body","getGraphQLBody","response","handlerClient","invoke","httpMethod","path","headers","Authorization","encodeToken","id","await","e","executeActionHandlerPlugins","config","ContextPlugin","register","PageBuilderGraphQL","HeadlessCMSGraphQL","basePlugins"],"sources":["index.ts"],"sourcesContent":["import { ApwScheduleActionData, ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport { getIsoStringTillMinutes, encodeToken, basePlugins } from \"~/scheduler/handlers/utils\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { PageBuilderGraphQL } from \"./plugins/PageBuilderGraphQL\";\nimport { HeadlessCMSGraphQL } from \"./plugins/HeadlessCMSGraphQL\";\nimport { ApplicationGraphQL } from \"./plugins/ApplicationGraphQL\";\nimport { createEvent } from \"@webiny/handler\";\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n futureDatetime?: string;\n}\n\ninterface Configuration {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\n/**\n * Handler that execute the provided action(s) for the schedule action workflow.\n */\nconst createExecuteActionLambda = (params: Configuration) => {\n const { storageOperations } = params;\n\n return createEvent<HandlerArgs>(async ({ payload, context }) => {\n const log = console.log;\n\n const applicationGraphQLPlugins = context.plugins.byType<ApplicationGraphQL>(\n ApplicationGraphQL.type\n );\n\n if (applicationGraphQLPlugins.length === 0) {\n console.error(`There are no plugins to determine GraphQL endpoints or mutations.`);\n return;\n }\n\n const applicationGraphQLPluginCache: Record<string, ApplicationGraphQL> = {};\n\n const getApplicationGraphQLPlugin = (\n data: ApwScheduleActionData\n ): ApplicationGraphQL | null => {\n const { type } = data;\n if (applicationGraphQLPluginCache[type]) {\n return applicationGraphQLPluginCache[type];\n }\n for (const plugin of applicationGraphQLPlugins) {\n if (!plugin.canUse(data)) {\n continue;\n }\n applicationGraphQLPluginCache[type] = plugin;\n return plugin;\n }\n return null;\n };\n\n try {\n const apwSettings = await getApwSettings();\n\n const { futureDatetime: datetime, locale, tenant } = payload;\n /**\n * If there is no datetime we bail out early.\n */\n if (!datetime || typeof datetime !== \"string\") {\n log(`Bailing out!!`);\n return;\n }\n\n /**\n * Get tasks from the DB by datetime.\n */\n const [items] = await storageOperations.list({\n where: {\n tenant,\n locale,\n datetime_startsWith: getIsoStringTillMinutes(datetime)\n },\n sort: [\"datetime_ASC\"],\n limit: 1000\n });\n\n /**\n * Execute all actions.\n */\n if (!items || items.length === 0) {\n return;\n }\n log(`Found ${items.length} actions.`);\n for (const item of items) {\n log(\n `Performing mutation \"${item.data.action}\" on \"${item.data.type}\" at \"${item.data.datetime}\"`\n );\n\n const plugin = getApplicationGraphQLPlugin(item.data);\n if (!plugin) {\n console.error(\n `There is no plugin to determine GraphQL endpoint and mutations for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const name = plugin.getArn(apwSettings);\n if (!name) {\n console.error(`There is no FunctionName found for type \"${item.data.type}\".`);\n console.log(\n JSON.stringify({\n item,\n settings: apwSettings\n })\n );\n continue;\n }\n\n const url = plugin.getUrl({\n locale,\n tenant\n });\n if (!url) {\n console.error(\n `There is no url defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const body = plugin.getGraphQLBody(item.data);\n\n if (!body) {\n console.error(\n `There is no GraphQL body defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n // Perform the actual action call.\n const response = await context.handlerClient.invoke({\n name,\n payload: {\n httpMethod: \"POST\",\n path: url,\n headers: {\n [\"content-type\"]: \"application/json\",\n Authorization: encodeToken({\n id: item.id,\n locale: item.locale,\n tenant: item.tenant\n }),\n [\"x-tenant\"]: tenant,\n [\"x-i18n-locale\"]: `default:${locale};content:${locale};`\n },\n body: JSON.stringify(body)\n },\n await: true\n });\n if (response?.body) {\n console.log(JSON.stringify({ body: response.body }, null, 2));\n continue;\n }\n console.log(JSON.stringify({ response }, null, 2));\n\n // TODO: Maybe update the status like error in original item in DB.\n }\n } catch (e) {\n log(\"[HANDLER_EXECUTE_ACTION] Error => \", e);\n // TODO: Maybe update the status like error in original item in DB.\n }\n });\n};\n\nexport const executeActionHandlerPlugins = (config: Configuration) => [\n new ContextPlugin(async context => {\n context.plugins.register([new PageBuilderGraphQL(), new HeadlessCMSGraphQL()]);\n }),\n basePlugins(),\n createExecuteActionLambda(config)\n];\n"],"mappings":";;;;;;AACA;AAEA;AACA;AACA;AACA;AACA;AAaA;AACA;AACA;AACA,MAAMA,yBAAyB,GAAIC,MAAqB,IAAK;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C,SAAS,CAAC;UAAEQ;QAAS,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;;QAElD;MACJ;IACJ,CAAC,CAAC,OAAOU,CAAC,EAAE;MACRhD,GAAG,CAAC,oCAAoC,EAAEgD,CAAC,CAAC;MAC5C;IACJ;EACJ,CAAC,CAAC;AACN,CAAC;;AAEM,MAAMC,2BAA2B,GAAIC,MAAqB,IAAK,CAClE,IAAIC,kBAAa,CAAC,MAAMpD,OAAO,IAAI;EAC/BA,OAAO,CAACI,OAAO,CAACiD,QAAQ,CAAC,CAAC,IAAIC,sCAAkB,EAAE,EAAE,IAAIC,sCAAkB,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,EACF,IAAAC,kBAAW,GAAE,EACb7D,yBAAyB,CAACwD,MAAM,CAAC,CACpC;AAAC"}
|
1
|
+
{"version":3,"names":["createExecuteActionLambda","params","storageOperations","createRawEventHandler","payload","context","log","console","applicationGraphQLPlugins","plugins","byType","ApplicationGraphQL","type","length","error","applicationGraphQLPluginCache","getApplicationGraphQLPlugin","data","plugin","canUse","apwSettings","getApwSettings","futureDatetime","datetime","locale","tenant","items","list","where","datetime_startsWith","getIsoStringTillMinutes","sort","limit","item","action","JSON","stringify","name","getArn","settings","url","getUrl","body","getGraphQLBody","response","handlerClient","invoke","httpMethod","path","headers","Authorization","encodeToken","id","await","delete","content","e","executeActionHandlerPlugins","config","ContextPlugin","register","PageBuilderGraphQL","HeadlessCMSGraphQL","basePlugins"],"sources":["index.ts"],"sourcesContent":["import { ApwScheduleActionData, ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport { getIsoStringTillMinutes, encodeToken, basePlugins } from \"~/scheduler/handlers/utils\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { PageBuilderGraphQL } from \"./plugins/PageBuilderGraphQL\";\nimport { HeadlessCMSGraphQL } from \"./plugins/HeadlessCMSGraphQL\";\nimport { ApplicationGraphQL } from \"./plugins/ApplicationGraphQL\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n futureDatetime?: string;\n}\n\ninterface Configuration {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\n/**\n * Handler that execute the provided action(s) for the schedule action workflow.\n */\nconst createExecuteActionLambda = (params: Configuration) => {\n const { storageOperations } = params;\n\n return createRawEventHandler<HandlerArgs>(async ({ payload, context }) => {\n const log = console.log;\n\n const applicationGraphQLPlugins = context.plugins.byType<ApplicationGraphQL>(\n ApplicationGraphQL.type\n );\n\n if (applicationGraphQLPlugins.length === 0) {\n console.error(`There are no plugins to determine GraphQL endpoints or mutations.`);\n return;\n }\n\n const applicationGraphQLPluginCache: Record<string, ApplicationGraphQL> = {};\n\n const getApplicationGraphQLPlugin = (\n data: ApwScheduleActionData\n ): ApplicationGraphQL | null => {\n const { type } = data;\n if (applicationGraphQLPluginCache[type]) {\n return applicationGraphQLPluginCache[type];\n }\n for (const plugin of applicationGraphQLPlugins) {\n if (!plugin.canUse(data)) {\n continue;\n }\n applicationGraphQLPluginCache[type] = plugin;\n return plugin;\n }\n return null;\n };\n\n try {\n const apwSettings = await getApwSettings();\n\n const { futureDatetime: datetime, locale, tenant } = payload;\n /**\n * If there is no datetime we bail out early.\n */\n if (!datetime || typeof datetime !== \"string\") {\n log(`Bailing out!!`);\n return;\n }\n\n /**\n * Get tasks from the DB by datetime.\n */\n const [items] = await storageOperations.list({\n where: {\n tenant,\n locale,\n datetime_startsWith: getIsoStringTillMinutes(datetime)\n },\n sort: [\"datetime_ASC\"],\n limit: 1000\n });\n\n /**\n * Execute all actions.\n */\n if (!items || items.length === 0) {\n return;\n }\n log(`Found ${items.length} actions.`);\n for (const item of items) {\n log(\n `Performing mutation \"${item.data.action}\" on \"${item.data.type}\" at \"${item.data.datetime}\"`\n );\n\n const plugin = getApplicationGraphQLPlugin(item.data);\n if (!plugin) {\n console.error(\n `There is no plugin to determine GraphQL endpoint and mutations for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const name = plugin.getArn(apwSettings);\n if (!name) {\n console.error(`There is no FunctionName found for type \"${item.data.type}\".`);\n console.log(\n JSON.stringify({\n item,\n settings: apwSettings\n })\n );\n continue;\n }\n\n const url = plugin.getUrl({\n locale,\n tenant\n });\n if (!url) {\n console.error(\n `There is no url defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const body = plugin.getGraphQLBody(item.data);\n\n if (!body) {\n console.error(\n `There is no GraphQL body defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n console.log(`Invoking Lambda \"${name}\" with url \"${url}\".`);\n // Perform the actual action call.\n const response = await context.handlerClient.invoke({\n name,\n payload: {\n httpMethod: \"POST\",\n path: url,\n headers: {\n [\"content-type\"]: \"application/json\",\n Authorization: encodeToken({\n id: item.id,\n locale: item.locale,\n tenant: item.tenant\n }),\n [\"x-tenant\"]: tenant,\n [\"x-i18n-locale\"]: `default:${locale};content:${locale};`\n },\n body: JSON.stringify(body)\n },\n await: true\n });\n /**\n *\n */\n await storageOperations.delete({\n locale,\n tenant,\n id: item.id\n });\n /**\n * Check for the response and log the error if any.\n */\n if (response?.body) {\n const error = response.body.data?.content?.error;\n if (!error) {\n console.log(\"Invoke successful.\");\n continue;\n }\n console.log(JSON.stringify({ error }, null, 2));\n continue;\n }\n console.log(JSON.stringify({ response }, null, 2));\n\n // TODO: Maybe update the status like error in original item in DB.\n }\n } catch (e) {\n log(\"[HANDLER_EXECUTE_ACTION] Error => \", e);\n // TODO: Maybe update the status like error in original item in DB.\n }\n });\n};\n\nexport const executeActionHandlerPlugins = (config: Configuration) => [\n new ContextPlugin(async context => {\n context.plugins.register([new PageBuilderGraphQL(), new HeadlessCMSGraphQL()]);\n }),\n basePlugins(),\n createExecuteActionLambda(config)\n];\n"],"mappings":";;;;;;AACA;AAE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AI,CAACmB;QACb,CAAC,CAAC;QACF;AAChB;AACA;QACgB,IAAIR,QAAQ,aAARA,QAAQ,eAARA,QAAQ,CAAEF,IAAI,EAAE;UAAA;UAChB,MAAM5B,KAAK,0BAAG8B,QAAQ,CAACF,IAAI,CAACzB,IAAI,iFAAlB,oBAAoBsC,OAAO,0DAA3B,sBAA6BzC,KAAK;UAChD,IAAI,CAACA,KAAK,EAAE;YACRP,OAAO,CAACD,GAAG,CAAC,oBAAoB,CAAC;YACjC;UACJ;UACAC,OAAO,CAACD,GAAG,CAAC6B,IAAI,CAACC,SAAS,CAAC;YAAEtB;UAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;UAC/C;QACJ;QACAP,OAAO,CAACD,GAAG,CAAC6B,IAAI,CAACC,SAAS,CAAC;UAAEQ;QAAS,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;;QAElD;MACJ;IACJ,CAAC,CAAC,OAAOY,CAAC,EAAE;MACRlD,GAAG,CAAC,oCAAoC,EAAEkD,CAAC,CAAC;MAC5C;IACJ;EACJ,CAAC,CAAC;AACN,CAAC;;AAEM,MAAMC,2BAA2B,GAAIC,MAAqB,IAAK,CAClE,IAAIC,kBAAa,CAAC,MAAMtD,OAAO,IAAI;EAC/BA,OAAO,CAACI,OAAO,CAACmD,QAAQ,CAAC,CAAC,IAAIC,sCAAkB,EAAE,EAAE,IAAIC,sCAAkB,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,EACF,IAAAC,kBAAW,GAAE,EACb/D,yBAAyB,CAAC0D,MAAM,CAAC,CACpC;AAAC"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["log","console","scheduleLambdaExecution","cloudWatchEventClient","invokedFunctionArn","datetime","futureDatetime","tenant","locale","eventTargetId","eventRuleName","getApwSettings","removeTargetsCommand","RemoveTargetsCommand","Rule","Ids","removeTargetsResponse","send","FailedEntryCount","info","FailedEntries","deleteRuleCommand","DeleteRuleCommand","Name","cronExpression","dateTimeToCronExpression","ruleParams","ScheduleExpression","State","Description","PutRuleCommand","PutTargetsCommand","Targets","Arn","Id","Input","JSON","stringify","invocationType","InvocationTypes","SCHEDULED","shouldScheduleTask","nextTaskDatetime","currentTaskDatetime","restoreDateTime","task","currentTask","storageOperations","id","item","get","where","newDateTime","moveDateTimeToCurrentCentury","data","update","input","executeTask","args","lambdaName","handlerClient","Date","toISOString","invoke","name","payload","await","deleteCurrentTask","e","error"],"sources":["scheduleAction.utils.ts"],"sourcesContent":["import { dateTimeToCronExpression, moveDateTimeToCurrentCentury } from \"~/scheduler/handlers/utils\";\nimport { ApwScheduleAction } from \"~/scheduler/types\";\nimport {\n HandlerArgs,\n InvocationTypes,\n Configuration\n} from \"~/scheduler/handlers/scheduleAction/index\";\nimport {\n DeleteRuleCommand,\n RemoveTargetsCommand,\n PutTargetsCommand,\n PutRuleCommand\n} from \"@aws-sdk/client-cloudwatch-events\";\nimport { ClientContext } from \"@webiny/handler-client/types\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst log = console.log;\n\ninterface ScheduleLambdaExecutionParams extends Omit<HandlerArgs, \"invocationType\"> {\n cloudWatchEventClient: any;\n invokedFunctionArn: string;\n}\n\n/**\n * Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;\n * in case of scheduling becoming the most frequently used feature.\n * https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/\n */\nexport async function scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn,\n datetime,\n futureDatetime,\n tenant,\n locale\n}: ScheduleLambdaExecutionParams) {\n const { eventTargetId, eventRuleName } = await getApwSettings();\n /**\n * Remove the target\n */\n const removeTargetsCommand = new RemoveTargetsCommand({\n Rule: eventRuleName,\n Ids: [eventTargetId]\n });\n const removeTargetsResponse = await cloudWatchEventClient.send(removeTargetsCommand);\n /**\n * Log error.\n */\n if (\n typeof removeTargetsResponse.FailedEntryCount === \"number\" &&\n removeTargetsResponse.FailedEntryCount !== 0\n ) {\n console.info(\"Failed in removing the targets!\");\n console.info(removeTargetsResponse.FailedEntries);\n }\n /**\n * Delete the Rule\n */\n const deleteRuleCommand = new DeleteRuleCommand({\n Name: eventRuleName\n });\n await cloudWatchEventClient.send(deleteRuleCommand);\n\n /**\n * Create a new one.\n * Min H D M DW Y\n * 20 10 10 03 * 2022\n */\n const cronExpression = dateTimeToCronExpression(datetime);\n\n const ruleParams = {\n Name: eventRuleName,\n ScheduleExpression: `cron(${cronExpression})`,\n State: \"ENABLED\",\n Description: `Enable us to schedule an action in publishing workflow at a particular datetime`\n };\n\n await cloudWatchEventClient.send(new PutRuleCommand(ruleParams));\n /**\n * Add lambda as target for the rule.\n */\n await cloudWatchEventClient.send(\n new PutTargetsCommand({\n Rule: eventRuleName,\n Targets: [\n {\n Arn: invokedFunctionArn,\n Id: eventTargetId,\n Input: JSON.stringify({\n datetime: datetime,\n tenant: tenant,\n locale: locale,\n invocationType: InvocationTypes.SCHEDULED,\n futureDatetime: futureDatetime\n } as HandlerArgs)\n }\n ]\n })\n );\n}\n\nexport const shouldScheduleTask = (\n nextTaskDatetime: string,\n currentTaskDatetime: string | null\n): boolean => {\n return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;\n};\n\ninterface RestoreDateTimeParams\n extends Pick<Configuration, \"storageOperations\">,\n Pick<HandlerArgs, \"tenant\" | \"locale\"> {\n task: ApwScheduleAction;\n}\n\nexport const restoreDateTime = async ({\n locale,\n tenant,\n task: currentTask,\n storageOperations\n}: RestoreDateTimeParams): Promise<void> => {\n log(`Mark task \"${currentTask.id}\" as undone by restoring original \"datetime\".`);\n const item = await storageOperations.get({\n where: {\n tenant,\n locale,\n id: currentTask.id\n }\n });\n if (item) {\n const newDateTime = moveDateTimeToCurrentCentury(item.data.datetime);\n await storageOperations.update({\n item: {\n ...item,\n data: { ...item.data, datetime: newDateTime }\n },\n input: { ...item.data, datetime: newDateTime }\n });\n }\n};\n\ninterface ExecuteTaskParams\n extends Pick<ClientContext, \"handlerClient\">,\n Pick<Configuration, \"storageOperations\"> {\n args: HandlerArgs;\n lambdaName: string;\n}\n\nexport const executeTask = async ({\n args,\n lambdaName,\n handlerClient,\n storageOperations\n}: ExecuteTaskParams): Promise<void> => {\n log(`Executing task at: `, new Date().toISOString());\n\n if (typeof handlerClient.invoke === \"function\") {\n await handlerClient.invoke({\n name: lambdaName,\n payload: {\n futureDatetime: args.futureDatetime,\n datetime: args.datetime,\n tenant: args.tenant,\n locale: args.locale\n },\n await: false\n });\n }\n\n /**\n * Delete current schedule Task. So that, we can schedule a new one later.\n */\n try {\n await storageOperations.deleteCurrentTask({\n tenant: args.tenant,\n locale: args.locale\n });\n } catch (e) {\n console.error(e);\n }\n};\n"],"mappings":";;;;;;;;;;AAAA;AAEA;AAKA;AASA,MAAMA,GAAG,GAAGC,OAAO,CAACD,GAAG;AAOvB;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAuB,CAAC;EAC1CC,qBAAqB;EACrBC,kBAAkB;EAClBC,QAAQ;EACRC,cAAc;EACdC,MAAM;EACNC;AAC2B,CAAC,EAAE;EAC9B,MAAM;IAAEC,aAAa;IAAEC;EAAc,CAAC,GAAG,MAAM,IAAAC,qBAAc,GAAE;EAC/D;AACJ;AACA;EACI,MAAMC,oBAAoB,GAAG,IAAIC,4CAAoB,CAAC;IAClDC,IAAI,EAAEJ,aAAa;IACnBK,GAAG,EAAE,CAACN,aAAa;EACvB,CAAC,CAAC;EACF,MAAMO,qBAAqB,GAAG,MAAMb,qBAAqB,CAACc,IAAI,CAACL,oBAAoB,CAAC;EACpF;AACJ;AACA;EACI,IACI,OAAOI,qBAAqB,CAACE,gBAAgB,KAAK,QAAQ,IAC1DF,qBAAqB,CAACE,gBAAgB,KAAK,CAAC,EAC9C;IACEjB,OAAO,CAACkB,IAAI,CAAC,iCAAiC,CAAC;IAC/ClB,OAAO,CAACkB,IAAI,CAACH,qBAAqB,CAACI,aAAa,CAAC;EACrD;EACA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GAAG,MAAMF,iBAAiB,CAACG,GAAG,CAAC;IACrCC,KAAK,EAAE;MACH5C,MAAM;MACNC,MAAM;MACNwC,EAAE,EAAEF,WAAW,CAACE;IACpB;EACJ,CAAC,CAAC;EACF,IAAIC,IAAI,EAAE;IACN,MAAMG,WAAW,GAAG,IAAAC,mCAA4B,EAACJ,IAAI,CAACK,IAAI,CAACjD,QAAQ,CAAC;IACpE,MAAM0C,iBAAiB,CAACQ,MAAM,CAAC;MAC3BN,IAAI,8DACGA,IAAI;QACPK,IAAI,8DAAOL,IAAI,CAACK,IAAI;UAAEjD,QAAQ,EAAE+C;QAAW;MAAE,EAChD;MACDI,KAAK,8DAAOP,IAAI,CAACK,IAAI;QAAEjD,QAAQ,EAAE+C;MAAW;IAChD,CAAC,CAAC;EACN;AACJ,CAAC;AAAC;AASK,MAAMK,WAAW,GAAG,OAAO;EAC9BC,IAAI;EACJC,UAAU;EACVC,aAAa;EACbb;AACe,CAAC,KAAoB;EACpC/C,GAAG,CAAE,qBAAoB,EAAE,IAAI6D,IAAI,EAAE,CAACC,WAAW,EAAE,CAAC;EAEpD,IAAI,OAAOF,aAAa,CAACG,MAAM,KAAK,UAAU,EAAE;IAC5C,MAAMH,aAAa,CAACG,MAAM,CAAC;MACvBC,IAAI,EAAEL,UAAU;MAChBM,OAAO,EAAE;QACL3D,cAAc,EAAEoD,IAAI,CAACpD,cAAc;QACnCD,QAAQ,EAAEqD,IAAI,CAACrD,QAAQ;QACvBE,MAAM,EAAEmD,IAAI,CAACnD,MAAM;QACnBC,MAAM,EAAEkD,IAAI,CAAClD;MACjB,CAAC;MACD0D,KAAK,EAAE;IACX,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;EACI,IAAI;IACA,
|
1
|
+
{"version":3,"names":["log","console","scheduleLambdaExecution","cloudWatchEventClient","invokedFunctionArn","datetime","futureDatetime","tenant","locale","eventTargetId","eventRuleName","getApwSettings","removeTargetsCommand","RemoveTargetsCommand","Rule","Ids","removeTargetsResponse","send","FailedEntryCount","info","FailedEntries","deleteRuleCommand","DeleteRuleCommand","Name","cronExpression","dateTimeToCronExpression","ruleParams","ScheduleExpression","State","Description","PutRuleCommand","PutTargetsCommand","Targets","Arn","Id","Input","JSON","stringify","invocationType","InvocationTypes","SCHEDULED","shouldScheduleTask","nextTaskDatetime","currentTaskDatetime","restoreDateTime","task","currentTask","storageOperations","id","item","get","where","newDateTime","moveDateTimeToCurrentCentury","data","update","input","executeTask","args","lambdaName","handlerClient","Date","toISOString","invoke","name","payload","await","deleteCurrentTask","e","error"],"sources":["scheduleAction.utils.ts"],"sourcesContent":["import { dateTimeToCronExpression, moveDateTimeToCurrentCentury } from \"~/scheduler/handlers/utils\";\nimport { ApwScheduleAction } from \"~/scheduler/types\";\nimport {\n HandlerArgs,\n InvocationTypes,\n Configuration\n} from \"~/scheduler/handlers/scheduleAction/index\";\nimport {\n DeleteRuleCommand,\n RemoveTargetsCommand,\n PutTargetsCommand,\n PutRuleCommand\n} from \"@aws-sdk/client-cloudwatch-events\";\nimport { ClientContext } from \"@webiny/handler-client/types\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst log = console.log;\n\ninterface ScheduleLambdaExecutionParams extends Omit<HandlerArgs, \"invocationType\"> {\n cloudWatchEventClient: any;\n invokedFunctionArn: string;\n}\n\n/**\n * Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;\n * in case of scheduling becoming the most frequently used feature.\n * https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/\n */\nexport async function scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn,\n datetime,\n futureDatetime,\n tenant,\n locale\n}: ScheduleLambdaExecutionParams) {\n const { eventTargetId, eventRuleName } = await getApwSettings();\n /**\n * Remove the target\n */\n const removeTargetsCommand = new RemoveTargetsCommand({\n Rule: eventRuleName,\n Ids: [eventTargetId]\n });\n const removeTargetsResponse = await cloudWatchEventClient.send(removeTargetsCommand);\n /**\n * Log error.\n */\n if (\n typeof removeTargetsResponse.FailedEntryCount === \"number\" &&\n removeTargetsResponse.FailedEntryCount !== 0\n ) {\n console.info(\"Failed in removing the targets!\");\n console.info(removeTargetsResponse.FailedEntries);\n }\n /**\n * Delete the Rule\n */\n const deleteRuleCommand = new DeleteRuleCommand({\n Name: eventRuleName\n });\n await cloudWatchEventClient.send(deleteRuleCommand);\n\n /**\n * Create a new one.\n * Min H D M DW Y\n * 20 10 10 03 * 2022\n */\n const cronExpression = dateTimeToCronExpression(datetime);\n\n const ruleParams = {\n Name: eventRuleName,\n ScheduleExpression: `cron(${cronExpression})`,\n State: \"ENABLED\",\n Description: `Enable us to schedule an action in publishing workflow at a particular datetime`\n };\n\n await cloudWatchEventClient.send(new PutRuleCommand(ruleParams));\n /**\n * Add lambda as target for the rule.\n */\n await cloudWatchEventClient.send(\n new PutTargetsCommand({\n Rule: eventRuleName,\n Targets: [\n {\n Arn: invokedFunctionArn,\n Id: eventTargetId,\n Input: JSON.stringify({\n datetime: datetime,\n tenant: tenant,\n locale: locale,\n invocationType: InvocationTypes.SCHEDULED,\n futureDatetime: futureDatetime\n } as HandlerArgs)\n }\n ]\n })\n );\n}\n\nexport const shouldScheduleTask = (\n nextTaskDatetime: string,\n currentTaskDatetime: string | null\n): boolean => {\n return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;\n};\n\ninterface RestoreDateTimeParams\n extends Pick<Configuration, \"storageOperations\">,\n Pick<HandlerArgs, \"tenant\" | \"locale\"> {\n task: ApwScheduleAction;\n}\n\nexport const restoreDateTime = async ({\n locale,\n tenant,\n task: currentTask,\n storageOperations\n}: RestoreDateTimeParams): Promise<void> => {\n log(`Mark task \"${currentTask.id}\" as undone by restoring original \"datetime\".`);\n const item = await storageOperations.get({\n where: {\n tenant,\n locale,\n id: currentTask.id\n }\n });\n if (item) {\n const newDateTime = moveDateTimeToCurrentCentury(item.data.datetime);\n await storageOperations.update({\n item: {\n ...item,\n data: { ...item.data, datetime: newDateTime }\n },\n input: { ...item.data, datetime: newDateTime }\n });\n }\n};\n\ninterface ExecuteTaskParams\n extends Pick<ClientContext, \"handlerClient\">,\n Pick<Configuration, \"storageOperations\"> {\n args: HandlerArgs;\n lambdaName: string;\n}\n\nexport const executeTask = async ({\n args,\n lambdaName,\n handlerClient,\n storageOperations\n}: ExecuteTaskParams): Promise<void> => {\n log(`Executing task at: `, new Date().toISOString());\n\n if (typeof handlerClient.invoke === \"function\") {\n await handlerClient.invoke({\n name: lambdaName,\n payload: {\n futureDatetime: args.futureDatetime,\n datetime: args.datetime,\n tenant: args.tenant,\n locale: args.locale\n },\n await: false\n });\n } else {\n console.log(`context.handlerClient.invoke is not a function!`);\n }\n\n /**\n * Delete current schedule Task. So that, we can schedule a new one later.\n */\n try {\n await storageOperations.deleteCurrentTask({\n tenant: args.tenant,\n locale: args.locale\n });\n } catch (e) {\n console.error(e);\n }\n};\n"],"mappings":";;;;;;;;;;AAAA;AAEA;AAKA;AASA,MAAMA,GAAG,GAAGC,OAAO,CAACD,GAAG;AAOvB;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAuB,CAAC;EAC1CC,qBAAqB;EACrBC,kBAAkB;EAClBC,QAAQ;EACRC,cAAc;EACdC,MAAM;EACNC;AAC2B,CAAC,EAAE;EAC9B,MAAM;IAAEC,aAAa;IAAEC;EAAc,CAAC,GAAG,MAAM,IAAAC,qBAAc,GAAE;EAC/D;AACJ;AACA;EACI,MAAMC,oBAAoB,GAAG,IAAIC,4CAAoB,CAAC;IAClDC,IAAI,EAAEJ,aAAa;IACnBK,GAAG,EAAE,CAACN,aAAa;EACvB,CAAC,CAAC;EACF,MAAMO,qBAAqB,GAAG,MAAMb,qBAAqB,CAACc,IAAI,CAACL,oBAAoB,CAAC;EACpF;AACJ;AACA;EACI,IACI,OAAOI,qBAAqB,CAACE,gBAAgB,KAAK,QAAQ,IAC1DF,qBAAqB,CAACE,gBAAgB,KAAK,CAAC,EAC9C;IACEjB,OAAO,CAACkB,IAA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