@webiny/api-apw 0.0.0-unstable.5e7233243f
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/ContentApwSettingsPlugin.d.ts +10 -0
- package/ContentApwSettingsPlugin.js +17 -0
- package/ContentApwSettingsPlugin.js.map +1 -0
- package/LICENSE +21 -0
- package/README.md +34 -0
- package/crud/createChangeRequestMethods.d.ts +2 -0
- package/crud/createChangeRequestMethods.js +95 -0
- package/crud/createChangeRequestMethods.js.map +1 -0
- package/crud/createCommentMethods.d.ts +2 -0
- package/crud/createCommentMethods.js +96 -0
- package/crud/createCommentMethods.js.map +1 -0
- package/crud/createContentReviewMethods.d.ts +10 -0
- package/crud/createContentReviewMethods.js +552 -0
- package/crud/createContentReviewMethods.js.map +1 -0
- package/crud/createReviewerMethods.d.ts +2 -0
- package/crud/createReviewerMethods.js +96 -0
- package/crud/createReviewerMethods.js.map +1 -0
- package/crud/createWorkflowMethods.d.ts +2 -0
- package/crud/createWorkflowMethods.js +96 -0
- package/crud/createWorkflowMethods.js.map +1 -0
- package/crud/index.d.ts +2 -0
- package/crud/index.js +100 -0
- package/crud/index.js.map +1 -0
- package/crud/utils.d.ts +21 -0
- package/crud/utils.js +142 -0
- package/crud/utils.js.map +1 -0
- package/index.d.ts +4 -0
- package/index.js +34 -0
- package/index.js.map +1 -0
- package/package.json +75 -0
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.d.ts +10 -0
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.js +51 -0
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.js.map +1 -0
- package/plugins/cms/README.md +49 -0
- package/plugins/cms/apwEntryPlugins.d.ts +8 -0
- package/plugins/cms/apwEntryPlugins.js +50 -0
- package/plugins/cms/apwEntryPlugins.js.map +1 -0
- package/plugins/cms/index.d.ts +12 -0
- package/plugins/cms/index.js +37 -0
- package/plugins/cms/index.js.map +1 -0
- package/plugins/cms/linkContentReviewToEntry.d.ts +8 -0
- package/plugins/cms/linkContentReviewToEntry.js +108 -0
- package/plugins/cms/linkContentReviewToEntry.js.map +1 -0
- package/plugins/cms/linkWorkflowToEntry.d.ts +8 -0
- package/plugins/cms/linkWorkflowToEntry.js +166 -0
- package/plugins/cms/linkWorkflowToEntry.js.map +1 -0
- package/plugins/cms/triggerContentReview.d.ts +8 -0
- package/plugins/cms/triggerContentReview.js +59 -0
- package/plugins/cms/triggerContentReview.js.map +1 -0
- package/plugins/cms/updateContentReviewStatus.d.ts +10 -0
- package/plugins/cms/updateContentReviewStatus.js +101 -0
- package/plugins/cms/updateContentReviewStatus.js.map +1 -0
- package/plugins/cms/utils.d.ts +27 -0
- package/plugins/cms/utils.js +211 -0
- package/plugins/cms/utils.js.map +1 -0
- package/plugins/context.d.ts +5 -0
- package/plugins/context.js +146 -0
- package/plugins/context.js.map +1 -0
- package/plugins/graphql/changeRequest.gql.d.ts +4 -0
- package/plugins/graphql/changeRequest.gql.js +155 -0
- package/plugins/graphql/changeRequest.gql.js.map +1 -0
- package/plugins/graphql/comment.gql.d.ts +4 -0
- package/plugins/graphql/comment.gql.js +160 -0
- package/plugins/graphql/comment.gql.js.map +1 -0
- package/plugins/graphql/contentReview.gql.d.ts +4 -0
- package/plugins/graphql/contentReview.gql.js +382 -0
- package/plugins/graphql/contentReview.gql.js.map +1 -0
- package/plugins/graphql/reviewer.gql.d.ts +4 -0
- package/plugins/graphql/reviewer.gql.js +114 -0
- package/plugins/graphql/reviewer.gql.js.map +1 -0
- package/plugins/graphql/workflow.gql.d.ts +4 -0
- package/plugins/graphql/workflow.gql.js +205 -0
- package/plugins/graphql/workflow.gql.js.map +1 -0
- package/plugins/graphql.d.ts +4 -0
- package/plugins/graphql.js +95 -0
- package/plugins/graphql.js.map +1 -0
- package/plugins/hooks/createReviewerFromIdentity.d.ts +2 -0
- package/plugins/hooks/createReviewerFromIdentity.js +62 -0
- package/plugins/hooks/createReviewerFromIdentity.js.map +1 -0
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.d.ts +2 -0
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.js +67 -0
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.js.map +1 -0
- package/plugins/hooks/deleteCommentsAfterChangeRequest.d.ts +2 -0
- package/plugins/hooks/deleteCommentsAfterChangeRequest.js +59 -0
- package/plugins/hooks/deleteCommentsAfterChangeRequest.js.map +1 -0
- package/plugins/hooks/index.d.ts +3 -0
- package/plugins/hooks/index.js +68 -0
- package/plugins/hooks/index.js.map +1 -0
- package/plugins/hooks/initializeContentReviewSteps.d.ts +2 -0
- package/plugins/hooks/initializeContentReviewSteps.js +89 -0
- package/plugins/hooks/initializeContentReviewSteps.js.map +1 -0
- package/plugins/hooks/updatePendingChangeRequests.d.ts +2 -0
- package/plugins/hooks/updatePendingChangeRequests.js +98 -0
- package/plugins/hooks/updatePendingChangeRequests.js.map +1 -0
- package/plugins/hooks/updateTotalComments.d.ts +3 -0
- package/plugins/hooks/updateTotalComments.js +157 -0
- package/plugins/hooks/updateTotalComments.js.map +1 -0
- package/plugins/hooks/validateChangeRequest.d.ts +2 -0
- package/plugins/hooks/validateChangeRequest.js +64 -0
- package/plugins/hooks/validateChangeRequest.js.map +1 -0
- package/plugins/hooks/validateComment.d.ts +2 -0
- package/plugins/hooks/validateComment.js +47 -0
- package/plugins/hooks/validateComment.js.map +1 -0
- package/plugins/hooks/validateContentReview.d.ts +2 -0
- package/plugins/hooks/validateContentReview.js +38 -0
- package/plugins/hooks/validateContentReview.js.map +1 -0
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.d.ts +9 -0
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.js +51 -0
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.js.map +1 -0
- package/plugins/pageBuilder/apwContentPagePlugins.d.ts +3 -0
- package/plugins/pageBuilder/apwContentPagePlugins.js +30 -0
- package/plugins/pageBuilder/apwContentPagePlugins.js.map +1 -0
- package/plugins/pageBuilder/extendPbPageSettingsSchema.d.ts +3 -0
- package/plugins/pageBuilder/extendPbPageSettingsSchema.js +25 -0
- package/plugins/pageBuilder/extendPbPageSettingsSchema.js.map +1 -0
- package/plugins/pageBuilder/index.d.ts +11 -0
- package/plugins/pageBuilder/index.js +45 -0
- package/plugins/pageBuilder/index.js.map +1 -0
- package/plugins/pageBuilder/linkContentReviewToPage.d.ts +8 -0
- package/plugins/pageBuilder/linkContentReviewToPage.js +93 -0
- package/plugins/pageBuilder/linkContentReviewToPage.js.map +1 -0
- package/plugins/pageBuilder/linkWorkflowToPage.d.ts +8 -0
- package/plugins/pageBuilder/linkWorkflowToPage.js +182 -0
- package/plugins/pageBuilder/linkWorkflowToPage.js.map +1 -0
- package/plugins/pageBuilder/triggerContentReview.d.ts +8 -0
- package/plugins/pageBuilder/triggerContentReview.js +50 -0
- package/plugins/pageBuilder/triggerContentReview.js.map +1 -0
- package/plugins/pageBuilder/updateContentReviewStatus.d.ts +10 -0
- package/plugins/pageBuilder/updateContentReviewStatus.js +83 -0
- package/plugins/pageBuilder/updateContentReviewStatus.js.map +1 -0
- package/plugins/pageBuilder/utils.d.ts +22 -0
- package/plugins/pageBuilder/utils.js +184 -0
- package/plugins/pageBuilder/utils.js.map +1 -0
- package/plugins/utils.d.ts +35 -0
- package/plugins/utils.js +197 -0
- package/plugins/utils.js.map +1 -0
- package/scheduler/createScheduleActionMethods.d.ts +2 -0
- package/scheduler/createScheduleActionMethods.js +146 -0
- package/scheduler/createScheduleActionMethods.js.map +1 -0
- package/scheduler/handlers/executeAction/index.d.ts +13 -0
- package/scheduler/handlers/executeAction/index.js +172 -0
- package/scheduler/handlers/executeAction/index.js.map +1 -0
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.d.ts +13 -0
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.js +17 -0
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.js.map +1 -0
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.d.ts +11 -0
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.js +126 -0
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.js.map +1 -0
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.d.ts +11 -0
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.js +163 -0
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.js.map +1 -0
- package/scheduler/handlers/executeAction/security.d.ts +4 -0
- package/scheduler/handlers/executeAction/security.js +68 -0
- package/scheduler/handlers/executeAction/security.js.map +1 -0
- package/scheduler/handlers/scheduleAction/index.d.ts +22 -0
- package/scheduler/handlers/scheduleAction/index.js +165 -0
- package/scheduler/handlers/scheduleAction/index.js.map +1 -0
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.d.ts +24 -0
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js +176 -0
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js.map +1 -0
- package/scheduler/handlers/utils.d.ts +33 -0
- package/scheduler/handlers/utils.js +168 -0
- package/scheduler/handlers/utils.js.map +1 -0
- package/scheduler/index.d.ts +2 -0
- package/scheduler/index.js +27 -0
- package/scheduler/index.js.map +1 -0
- package/scheduler/types.d.ts +171 -0
- package/scheduler/types.js +34 -0
- package/scheduler/types.js.map +1 -0
- package/storageOperations/changeRequestStorageOperations.d.ts +3 -0
- package/storageOperations/changeRequestStorageOperations.js +126 -0
- package/storageOperations/changeRequestStorageOperations.js.map +1 -0
- package/storageOperations/commentStorageOperations.d.ts +3 -0
- package/storageOperations/commentStorageOperations.js +142 -0
- package/storageOperations/commentStorageOperations.js.map +1 -0
- package/storageOperations/contentReviewStorageOperations.d.ts +3 -0
- package/storageOperations/contentReviewStorageOperations.js +97 -0
- package/storageOperations/contentReviewStorageOperations.js.map +1 -0
- package/storageOperations/index.d.ts +15 -0
- package/storageOperations/index.js +52 -0
- package/storageOperations/index.js.map +1 -0
- package/storageOperations/models/changeRequest.model.d.ts +3 -0
- package/storageOperations/models/changeRequest.model.js +59 -0
- package/storageOperations/models/changeRequest.model.js.map +1 -0
- package/storageOperations/models/comment.model.d.ts +7 -0
- package/storageOperations/models/comment.model.js +60 -0
- package/storageOperations/models/comment.model.js.map +1 -0
- package/storageOperations/models/contentModelPluginFactory.d.ts +15 -0
- package/storageOperations/models/contentModelPluginFactory.js +32 -0
- package/storageOperations/models/contentModelPluginFactory.js.map +1 -0
- package/storageOperations/models/contentReview.model.d.ts +7 -0
- package/storageOperations/models/contentReview.model.js +257 -0
- package/storageOperations/models/contentReview.model.js.map +1 -0
- package/storageOperations/models/index.d.ts +2 -0
- package/storageOperations/models/index.js +115 -0
- package/storageOperations/models/index.js.map +1 -0
- package/storageOperations/models/reviewer.model.d.ts +3 -0
- package/storageOperations/models/reviewer.model.js +55 -0
- package/storageOperations/models/reviewer.model.js.map +1 -0
- package/storageOperations/models/utils.d.ts +3 -0
- package/storageOperations/models/utils.js +36 -0
- package/storageOperations/models/utils.js.map +1 -0
- package/storageOperations/models/workflow.model.d.ts +12 -0
- package/storageOperations/models/workflow.model.js +208 -0
- package/storageOperations/models/workflow.model.js.map +1 -0
- package/storageOperations/reviewerStorageOperations.d.ts +3 -0
- package/storageOperations/reviewerStorageOperations.js +93 -0
- package/storageOperations/reviewerStorageOperations.js.map +1 -0
- package/storageOperations/types.d.ts +34 -0
- package/storageOperations/types.js +5 -0
- package/storageOperations/types.js.map +1 -0
- package/storageOperations/workflowStorageOperations.d.ts +3 -0
- package/storageOperations/workflowStorageOperations.js +115 -0
- package/storageOperations/workflowStorageOperations.js.map +1 -0
- package/types.d.ts +737 -0
- package/types.js +69 -0
- package/types.js.map +1 -0
- package/utils/contentApwSettingsPlugin.d.ts +9 -0
- package/utils/contentApwSettingsPlugin.js +26 -0
- package/utils/contentApwSettingsPlugin.js.map +1 -0
- package/utils/errors.d.ts +16 -0
- package/utils/errors.js +75 -0
- package/utils/errors.js.map +1 -0
- package/utils/fieldResolver.d.ts +16 -0
- package/utils/fieldResolver.js +60 -0
- package/utils/fieldResolver.js.map +1 -0
- package/utils/resolve.d.ts +3 -0
- package/utils/resolve.js +18 -0
- package/utils/resolve.js.map +1 -0
@@ -0,0 +1,22 @@
|
|
1
|
+
/**
|
2
|
+
* This logic/file should be moved somewhere else as it is relying on AWS specific stuff.
|
3
|
+
*/
|
4
|
+
import { ApwScheduleActionStorageOperations } from "../../types";
|
5
|
+
export declare enum InvocationTypes {
|
6
|
+
SCHEDULED = "scheduled"
|
7
|
+
}
|
8
|
+
export interface HandlerArgs {
|
9
|
+
datetime: string;
|
10
|
+
tenant: string;
|
11
|
+
locale: string;
|
12
|
+
invocationType?: InvocationTypes;
|
13
|
+
futureDatetime?: string;
|
14
|
+
}
|
15
|
+
export interface Configuration {
|
16
|
+
cwClient: any;
|
17
|
+
storageOperations: ApwScheduleActionStorageOperations;
|
18
|
+
handlers: {
|
19
|
+
executeAction: string;
|
20
|
+
};
|
21
|
+
}
|
22
|
+
export declare const scheduleActionHandlerPlugins: (config: Configuration) => ((import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | import("@webiny/api").ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[] | import("@webiny/handler-aws").RawEventHandler<HandlerArgs, import("@webiny/handler/types").Context, any>)[];
|
@@ -0,0 +1,165 @@
|
|
1
|
+
"use strict";
|
2
|
+
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
+
|
5
|
+
Object.defineProperty(exports, "__esModule", {
|
6
|
+
value: true
|
7
|
+
});
|
8
|
+
exports.scheduleActionHandlerPlugins = exports.InvocationTypes = void 0;
|
9
|
+
|
10
|
+
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
11
|
+
|
12
|
+
var _utils = require("../utils");
|
13
|
+
|
14
|
+
var _scheduleAction = require("./scheduleAction.utils");
|
15
|
+
|
16
|
+
var _handlerAws = require("@webiny/handler-aws");
|
17
|
+
|
18
|
+
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
|
19
|
+
|
20
|
+
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
|
21
|
+
|
22
|
+
let InvocationTypes;
|
23
|
+
exports.InvocationTypes = InvocationTypes;
|
24
|
+
|
25
|
+
(function (InvocationTypes) {
|
26
|
+
InvocationTypes["SCHEDULED"] = "scheduled";
|
27
|
+
})(InvocationTypes || (exports.InvocationTypes = InvocationTypes = {}));
|
28
|
+
|
29
|
+
const log = console.log;
|
30
|
+
/**
|
31
|
+
* Handler that creates a cloudwatch event rule for the schedule action workflow.
|
32
|
+
*/
|
33
|
+
|
34
|
+
const createScheduleActionLambda = params => {
|
35
|
+
const {
|
36
|
+
cwClient: cloudWatchEventClient,
|
37
|
+
storageOperations,
|
38
|
+
handlers
|
39
|
+
} = params;
|
40
|
+
return (0, _handlerAws.createRawEventHandler)(async ({
|
41
|
+
payload,
|
42
|
+
context,
|
43
|
+
lambdaContext: eventContext
|
44
|
+
}) => {
|
45
|
+
try {
|
46
|
+
const {
|
47
|
+
locale,
|
48
|
+
tenant,
|
49
|
+
invocationType
|
50
|
+
} = payload;
|
51
|
+
/**
|
52
|
+
* If invocationType is "scheduled", execute the action.
|
53
|
+
*/
|
54
|
+
|
55
|
+
if (invocationType === InvocationTypes.SCHEDULED) {
|
56
|
+
await (0, _scheduleAction.executeTask)({
|
57
|
+
args: payload,
|
58
|
+
lambdaName: handlers.executeAction,
|
59
|
+
handlerClient: context.handlerClient,
|
60
|
+
storageOperations
|
61
|
+
});
|
62
|
+
}
|
63
|
+
/**
|
64
|
+
* Get current scheduled task from the DB.
|
65
|
+
*/
|
66
|
+
|
67
|
+
|
68
|
+
const currentTask = await storageOperations.getCurrentTask({
|
69
|
+
where: {
|
70
|
+
tenant,
|
71
|
+
locale
|
72
|
+
}
|
73
|
+
});
|
74
|
+
/**
|
75
|
+
* Get next task from the DB.
|
76
|
+
*/
|
77
|
+
|
78
|
+
const [[nextItem]] = await storageOperations.list({
|
79
|
+
where: {
|
80
|
+
tenant,
|
81
|
+
locale
|
82
|
+
},
|
83
|
+
sort: ["datetime_ASC"],
|
84
|
+
limit: 1
|
85
|
+
});
|
86
|
+
|
87
|
+
if (!nextItem) {
|
88
|
+
log(`No item found.`);
|
89
|
+
return;
|
90
|
+
}
|
91
|
+
|
92
|
+
const nextTaskDatetime = nextItem.data.datetime;
|
93
|
+
const currentTaskDatetime = currentTask && currentTask.data.datetime;
|
94
|
+
|
95
|
+
if ((0, _utils.isDateTimeInNextCentury)(nextTaskDatetime)) {
|
96
|
+
log(`Already processed the task.`);
|
97
|
+
return;
|
98
|
+
}
|
99
|
+
|
100
|
+
if (!(0, _scheduleAction.shouldScheduleTask)(nextTaskDatetime, currentTaskDatetime)) {
|
101
|
+
log(`Already scheduled the task.`);
|
102
|
+
return;
|
103
|
+
}
|
104
|
+
|
105
|
+
const futureDatetime = (0, _utils.moveDateTimeToNextCentury)(nextItem.data.datetime);
|
106
|
+
/**
|
107
|
+
* Update "datetime" to a future date to mark it as scheduled.
|
108
|
+
*/
|
109
|
+
|
110
|
+
log(`Update task's datetime to `, futureDatetime);
|
111
|
+
await storageOperations.update({
|
112
|
+
item: _objectSpread(_objectSpread({}, nextItem), {}, {
|
113
|
+
data: _objectSpread(_objectSpread({}, nextItem.data), {}, {
|
114
|
+
datetime: futureDatetime
|
115
|
+
})
|
116
|
+
}),
|
117
|
+
input: _objectSpread(_objectSpread({}, nextItem.data), {}, {
|
118
|
+
datetime: futureDatetime
|
119
|
+
})
|
120
|
+
});
|
121
|
+
/**
|
122
|
+
* Restore "datetime" of current task so that it can be schedule in next cycle.
|
123
|
+
*/
|
124
|
+
|
125
|
+
if (currentTaskDatetime && (0, _utils.shouldRestoreDatetime)({
|
126
|
+
invocationType,
|
127
|
+
datetime: currentTaskDatetime
|
128
|
+
})) {
|
129
|
+
await (0, _scheduleAction.restoreDateTime)({
|
130
|
+
tenant,
|
131
|
+
locale,
|
132
|
+
task: currentTask,
|
133
|
+
storageOperations
|
134
|
+
});
|
135
|
+
}
|
136
|
+
/**
|
137
|
+
* Schedule Lambda
|
138
|
+
*/
|
139
|
+
|
140
|
+
|
141
|
+
log(`Schedule Lambda Execution...`);
|
142
|
+
await (0, _scheduleAction.scheduleLambdaExecution)({
|
143
|
+
cloudWatchEventClient,
|
144
|
+
invokedFunctionArn: eventContext.invokedFunctionArn,
|
145
|
+
datetime: nextItem.data.datetime,
|
146
|
+
futureDatetime: futureDatetime,
|
147
|
+
tenant,
|
148
|
+
locale
|
149
|
+
});
|
150
|
+
/**
|
151
|
+
* Update current task.
|
152
|
+
*/
|
153
|
+
|
154
|
+
await storageOperations.updateCurrentTask({
|
155
|
+
item: nextItem
|
156
|
+
});
|
157
|
+
} catch (ex) {
|
158
|
+
log("[HANDLER_CREATE_RULE] Error => ", ex); // TODO: Handler error. Maybe save it into DB.
|
159
|
+
}
|
160
|
+
});
|
161
|
+
};
|
162
|
+
|
163
|
+
const scheduleActionHandlerPlugins = config => [(0, _utils.basePlugins)(), createScheduleActionLambda(config)];
|
164
|
+
|
165
|
+
exports.scheduleActionHandlerPlugins = scheduleActionHandlerPlugins;
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"names":["InvocationTypes","log","console","createScheduleActionLambda","params","cwClient","cloudWatchEventClient","storageOperations","handlers","createRawEventHandler","payload","context","lambdaContext","eventContext","locale","tenant","invocationType","SCHEDULED","executeTask","args","lambdaName","executeAction","handlerClient","currentTask","getCurrentTask","where","nextItem","list","sort","limit","nextTaskDatetime","data","datetime","currentTaskDatetime","isDateTimeInNextCentury","shouldScheduleTask","futureDatetime","moveDateTimeToNextCentury","update","item","input","shouldRestoreDatetime","restoreDateTime","task","scheduleLambdaExecution","invokedFunctionArn","updateCurrentTask","ex","scheduleActionHandlerPlugins","config","basePlugins"],"sources":["index.ts"],"sourcesContent":["/**\n * This logic/file should be moved somewhere else as it is relying on AWS specific stuff.\n */\nimport { ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport {\n isDateTimeInNextCentury,\n moveDateTimeToNextCentury,\n shouldRestoreDatetime,\n basePlugins\n} from \"~/scheduler/handlers/utils\";\nimport {\n executeTask,\n shouldScheduleTask,\n restoreDateTime,\n scheduleLambdaExecution\n} from \"./scheduleAction.utils\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport enum InvocationTypes {\n SCHEDULED = \"scheduled\"\n}\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n invocationType?: InvocationTypes;\n futureDatetime?: string;\n}\n\nexport interface Configuration {\n cwClient: any;\n storageOperations: ApwScheduleActionStorageOperations;\n handlers: {\n executeAction: string;\n };\n}\n\nconst log = console.log;\n\n/**\n * Handler that creates a cloudwatch event rule for the schedule action workflow.\n */\nconst createScheduleActionLambda = (params: Configuration) => {\n const { cwClient: cloudWatchEventClient, storageOperations, handlers } = params;\n\n return createRawEventHandler<HandlerArgs>(\n async ({ payload, context, lambdaContext: eventContext }) => {\n try {\n const { locale, tenant, invocationType } = payload;\n /**\n * If invocationType is \"scheduled\", execute the action.\n */\n if (invocationType === InvocationTypes.SCHEDULED) {\n await executeTask({\n args: payload,\n lambdaName: handlers.executeAction,\n handlerClient: context.handlerClient,\n storageOperations\n });\n }\n\n /**\n * Get current scheduled task from the DB.\n */\n const currentTask = await storageOperations.getCurrentTask({\n where: {\n tenant,\n locale\n }\n });\n\n /**\n * Get next task from the DB.\n */\n const [[nextItem]] = await storageOperations.list({\n where: {\n tenant,\n locale\n },\n sort: [\"datetime_ASC\"],\n limit: 1\n });\n\n if (!nextItem) {\n log(`No item found.`);\n return;\n }\n\n const nextTaskDatetime = nextItem.data.datetime;\n const currentTaskDatetime = currentTask && currentTask.data.datetime;\n\n if (isDateTimeInNextCentury(nextTaskDatetime)) {\n log(`Already processed the task.`);\n return;\n }\n\n if (!shouldScheduleTask(nextTaskDatetime, currentTaskDatetime)) {\n log(`Already scheduled the task.`);\n return;\n }\n\n const futureDatetime = moveDateTimeToNextCentury(nextItem.data.datetime);\n /**\n * Update \"datetime\" to a future date to mark it as scheduled.\n */\n log(`Update task's datetime to `, futureDatetime);\n await storageOperations.update({\n item: {\n ...nextItem,\n data: { ...nextItem.data, datetime: futureDatetime }\n },\n input: { ...nextItem.data, datetime: futureDatetime }\n });\n /**\n * Restore \"datetime\" of current task so that it can be schedule in next cycle.\n */\n if (\n currentTaskDatetime &&\n shouldRestoreDatetime({\n invocationType,\n datetime: currentTaskDatetime\n })\n ) {\n await restoreDateTime({\n tenant,\n locale,\n task: currentTask,\n storageOperations\n });\n }\n /**\n * Schedule Lambda\n */\n log(`Schedule Lambda Execution...`);\n await scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn: eventContext.invokedFunctionArn,\n datetime: nextItem.data.datetime,\n futureDatetime: futureDatetime,\n tenant,\n locale\n });\n /**\n * Update current task.\n */\n await storageOperations.updateCurrentTask({ item: nextItem });\n } catch (ex) {\n log(\"[HANDLER_CREATE_RULE] Error => \", ex);\n // TODO: Handler error. Maybe save it into DB.\n }\n }\n );\n};\n\nexport const scheduleActionHandlerPlugins = (config: Configuration) => [\n basePlugins(),\n createScheduleActionLambda(config)\n];\n"],"mappings":";;;;;;;;;;;AAIA;;AAMA;;AAMA;;;;;;IAEYA,e;;;WAAAA,e;EAAA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AAlB,CAAoC;QAAEP,IAAI,EAAEb;MAAR,CAApC,CAAN;IACH,CAnGD,CAmGE,OAAOqB,EAAP,EAAW;MACT9C,GAAG,CAAC,iCAAD,EAAoC8C,EAApC,CAAH,CADS,CAET;IACH;EACJ,CAzGE,CAAP;AA2GH,CA9GD;;AAgHO,MAAMC,4BAA4B,GAAIC,MAAD,IAA2B,CACnE,IAAAC,kBAAA,GADmE,EAEnE/C,0BAA0B,CAAC8C,MAAD,CAFyC,CAAhE"}
|
@@ -0,0 +1,24 @@
|
|
1
|
+
import { ApwScheduleAction } from "../../types";
|
2
|
+
import { HandlerArgs, Configuration } from "./index";
|
3
|
+
import { ClientContext } from "@webiny/handler-client/types";
|
4
|
+
interface ScheduleLambdaExecutionParams extends Omit<HandlerArgs, "invocationType"> {
|
5
|
+
cloudWatchEventClient: any;
|
6
|
+
invokedFunctionArn: string;
|
7
|
+
}
|
8
|
+
/**
|
9
|
+
* Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;
|
10
|
+
* in case of scheduling becoming the most frequently used feature.
|
11
|
+
* https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/
|
12
|
+
*/
|
13
|
+
export declare function scheduleLambdaExecution({ cloudWatchEventClient, invokedFunctionArn, datetime, futureDatetime, tenant, locale }: ScheduleLambdaExecutionParams): Promise<void>;
|
14
|
+
export declare const shouldScheduleTask: (nextTaskDatetime: string, currentTaskDatetime: string | null) => boolean;
|
15
|
+
interface RestoreDateTimeParams extends Pick<Configuration, "storageOperations">, Pick<HandlerArgs, "tenant" | "locale"> {
|
16
|
+
task: ApwScheduleAction;
|
17
|
+
}
|
18
|
+
export declare const restoreDateTime: ({ locale, tenant, task: currentTask, storageOperations }: RestoreDateTimeParams) => Promise<void>;
|
19
|
+
interface ExecuteTaskParams extends Pick<ClientContext, "handlerClient">, Pick<Configuration, "storageOperations"> {
|
20
|
+
args: HandlerArgs;
|
21
|
+
lambdaName: string;
|
22
|
+
}
|
23
|
+
export declare const executeTask: ({ args, lambdaName, handlerClient, storageOperations }: ExecuteTaskParams) => Promise<void>;
|
24
|
+
export {};
|
@@ -0,0 +1,176 @@
|
|
1
|
+
"use strict";
|
2
|
+
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
+
|
5
|
+
Object.defineProperty(exports, "__esModule", {
|
6
|
+
value: true
|
7
|
+
});
|
8
|
+
exports.restoreDateTime = exports.executeTask = void 0;
|
9
|
+
exports.scheduleLambdaExecution = scheduleLambdaExecution;
|
10
|
+
exports.shouldScheduleTask = void 0;
|
11
|
+
|
12
|
+
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
13
|
+
|
14
|
+
var _utils = require("../utils");
|
15
|
+
|
16
|
+
var _index = require("./index");
|
17
|
+
|
18
|
+
var _clientCloudwatchEvents = require("@aws-sdk/client-cloudwatch-events");
|
19
|
+
|
20
|
+
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
|
21
|
+
|
22
|
+
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
|
23
|
+
|
24
|
+
const log = console.log;
|
25
|
+
|
26
|
+
/**
|
27
|
+
* Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;
|
28
|
+
* in case of scheduling becoming the most frequently used feature.
|
29
|
+
* https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/
|
30
|
+
*/
|
31
|
+
async function scheduleLambdaExecution({
|
32
|
+
cloudWatchEventClient,
|
33
|
+
invokedFunctionArn,
|
34
|
+
datetime,
|
35
|
+
futureDatetime,
|
36
|
+
tenant,
|
37
|
+
locale
|
38
|
+
}) {
|
39
|
+
const {
|
40
|
+
eventTargetId,
|
41
|
+
eventRuleName
|
42
|
+
} = await (0, _utils.getApwSettings)();
|
43
|
+
/**
|
44
|
+
* Remove the target
|
45
|
+
*/
|
46
|
+
|
47
|
+
const removeTargetsCommand = new _clientCloudwatchEvents.RemoveTargetsCommand({
|
48
|
+
Rule: eventRuleName,
|
49
|
+
Ids: [eventTargetId]
|
50
|
+
});
|
51
|
+
const removeTargetsResponse = await cloudWatchEventClient.send(removeTargetsCommand);
|
52
|
+
/**
|
53
|
+
* Log error.
|
54
|
+
*/
|
55
|
+
|
56
|
+
if (typeof removeTargetsResponse.FailedEntryCount === "number" && removeTargetsResponse.FailedEntryCount !== 0) {
|
57
|
+
console.info("Failed in removing the targets!");
|
58
|
+
console.info(removeTargetsResponse.FailedEntries);
|
59
|
+
}
|
60
|
+
/**
|
61
|
+
* Delete the Rule
|
62
|
+
*/
|
63
|
+
|
64
|
+
|
65
|
+
const deleteRuleCommand = new _clientCloudwatchEvents.DeleteRuleCommand({
|
66
|
+
Name: eventRuleName
|
67
|
+
});
|
68
|
+
await cloudWatchEventClient.send(deleteRuleCommand);
|
69
|
+
/**
|
70
|
+
* Create a new one.
|
71
|
+
* Min H D M DW Y
|
72
|
+
* 20 10 10 03 * 2022
|
73
|
+
*/
|
74
|
+
|
75
|
+
const cronExpression = (0, _utils.dateTimeToCronExpression)(datetime);
|
76
|
+
const ruleParams = {
|
77
|
+
Name: eventRuleName,
|
78
|
+
ScheduleExpression: `cron(${cronExpression})`,
|
79
|
+
State: "ENABLED",
|
80
|
+
Description: `Enable us to schedule an action in publishing workflow at a particular datetime`
|
81
|
+
};
|
82
|
+
await cloudWatchEventClient.send(new _clientCloudwatchEvents.PutRuleCommand(ruleParams));
|
83
|
+
/**
|
84
|
+
* Add lambda as target for the rule.
|
85
|
+
*/
|
86
|
+
|
87
|
+
await cloudWatchEventClient.send(new _clientCloudwatchEvents.PutTargetsCommand({
|
88
|
+
Rule: eventRuleName,
|
89
|
+
Targets: [{
|
90
|
+
Arn: invokedFunctionArn,
|
91
|
+
Id: eventTargetId,
|
92
|
+
Input: JSON.stringify({
|
93
|
+
datetime: datetime,
|
94
|
+
tenant: tenant,
|
95
|
+
locale: locale,
|
96
|
+
invocationType: _index.InvocationTypes.SCHEDULED,
|
97
|
+
futureDatetime: futureDatetime
|
98
|
+
})
|
99
|
+
}]
|
100
|
+
}));
|
101
|
+
}
|
102
|
+
|
103
|
+
const shouldScheduleTask = (nextTaskDatetime, currentTaskDatetime) => {
|
104
|
+
return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;
|
105
|
+
};
|
106
|
+
|
107
|
+
exports.shouldScheduleTask = shouldScheduleTask;
|
108
|
+
|
109
|
+
const restoreDateTime = async ({
|
110
|
+
locale,
|
111
|
+
tenant,
|
112
|
+
task: currentTask,
|
113
|
+
storageOperations
|
114
|
+
}) => {
|
115
|
+
log(`Mark task "${currentTask.id}" as undone by restoring original "datetime".`);
|
116
|
+
const item = await storageOperations.get({
|
117
|
+
where: {
|
118
|
+
tenant,
|
119
|
+
locale,
|
120
|
+
id: currentTask.id
|
121
|
+
}
|
122
|
+
});
|
123
|
+
|
124
|
+
if (item) {
|
125
|
+
const newDateTime = (0, _utils.moveDateTimeToCurrentCentury)(item.data.datetime);
|
126
|
+
await storageOperations.update({
|
127
|
+
item: _objectSpread(_objectSpread({}, item), {}, {
|
128
|
+
data: _objectSpread(_objectSpread({}, item.data), {}, {
|
129
|
+
datetime: newDateTime
|
130
|
+
})
|
131
|
+
}),
|
132
|
+
input: _objectSpread(_objectSpread({}, item.data), {}, {
|
133
|
+
datetime: newDateTime
|
134
|
+
})
|
135
|
+
});
|
136
|
+
}
|
137
|
+
};
|
138
|
+
|
139
|
+
exports.restoreDateTime = restoreDateTime;
|
140
|
+
|
141
|
+
const executeTask = async ({
|
142
|
+
args,
|
143
|
+
lambdaName,
|
144
|
+
handlerClient,
|
145
|
+
storageOperations
|
146
|
+
}) => {
|
147
|
+
log(`Executing task at: `, new Date().toISOString());
|
148
|
+
|
149
|
+
if (typeof handlerClient.invoke === "function") {
|
150
|
+
await handlerClient.invoke({
|
151
|
+
name: lambdaName,
|
152
|
+
payload: {
|
153
|
+
futureDatetime: args.futureDatetime,
|
154
|
+
datetime: args.datetime,
|
155
|
+
tenant: args.tenant,
|
156
|
+
locale: args.locale
|
157
|
+
},
|
158
|
+
await: false
|
159
|
+
});
|
160
|
+
}
|
161
|
+
/**
|
162
|
+
* Delete current schedule Task. So that, we can schedule a new one later.
|
163
|
+
*/
|
164
|
+
|
165
|
+
|
166
|
+
try {
|
167
|
+
await storageOperations.deleteCurrentTask({
|
168
|
+
tenant: args.tenant,
|
169
|
+
locale: args.locale
|
170
|
+
});
|
171
|
+
} catch (e) {
|
172
|
+
console.error(e);
|
173
|
+
}
|
174
|
+
};
|
175
|
+
|
176
|
+
exports.executeTask = executeTask;
|
@@ -0,0 +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,GAApB;;AAOA;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAf,CAAuC;EAC1CC,qBAD0C;EAE1CC,kBAF0C;EAG1CC,QAH0C;EAI1CC,cAJ0C;EAK1CC,MAL0C;EAM1CC;AAN0C,CAAvC,EAO2B;EAC9B,MAAM;IAAEC,aAAF;IAAiBC;EAAjB,IAAmC,MAAM,IAAAC,qBAAA,GAA/C;EACA;AACJ;AACA;;EACI,MAAMC,oBAAoB,GAAG,IAAIC,4CAAJ,CAAyB;IAClDC,IAAI,EAAEJ,aAD4C;IAElDK,GAAG,EAAE,CAACN,aAAD;EAF6C,CAAzB,CAA7B;EAIA,MAAMO,qBAAqB,GAAG,MAAMb,qBAAqB,CAACc,IAAtB,CAA2BL,oBAA3B,CAApC;EACA;AACJ;AACA;;EACI,IACI,OAAOI,qBAAqB,CAACE,gBAA7B,KAAkD,QAAlD,IACAF,qBAAqB,CAACE,gBAAtB,KAA2C,CAF/C,EAGE;IACEjB,OAAO,CAACkB,IAAR,CAAa,iCAAb;IACAlB,OAAO,CAACkB,IAAR,CAAaH,qBAAqB,CAACI,aAAnC;EACH;EACD;AACJ;AACA;;;EACI,MAAMC,iBAAiB,GAAG,IAAIC,yCAAJ,CAAsB;IAC5CC,IAAI,EAAEb;EADsC,CAAtB,CAA1B;EAGA,MAAMP,qBAAqB,CAACc,IAAtB,CAA2BI,iBAA3B,CAAN;EAEA;AACJ;AACA;AACA;AACA;;EACI,MAAMG,cAAc,GA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/clients/dynamodb";
|
2
|
+
import { InvocationTypes } from "../types";
|
3
|
+
export declare const getIsoStringTillMinutes: (datetime: string) => string;
|
4
|
+
export declare const dateTimeToCronExpression: (datetime: string) => string;
|
5
|
+
export declare const moveDateTimeToNextCentury: (datetime: string) => string;
|
6
|
+
export declare const moveDateTimeToCurrentCentury: (datetime: string) => string;
|
7
|
+
export declare const isDateTimeInNextCentury: (datetime: string) => boolean;
|
8
|
+
interface ShouldRestoreDatetimeParams {
|
9
|
+
invocationType?: InvocationTypes;
|
10
|
+
datetime: string;
|
11
|
+
}
|
12
|
+
export declare const shouldRestoreDatetime: ({ invocationType, datetime }: ShouldRestoreDatetimeParams) => boolean;
|
13
|
+
interface EncodeTokenParams {
|
14
|
+
id: string;
|
15
|
+
tenant: string;
|
16
|
+
locale: string;
|
17
|
+
}
|
18
|
+
export declare const encodeToken: ({ id, tenant, locale }: EncodeTokenParams) => string;
|
19
|
+
export declare const TOKEN_PREFIX = "apw-";
|
20
|
+
export declare const decodeToken: (token: string) => Partial<EncodeTokenParams>;
|
21
|
+
export declare const documentClient: DocumentClient;
|
22
|
+
export declare const basePlugins: () => (import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | import("@webiny/api").ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[];
|
23
|
+
/**
|
24
|
+
* Get APW settings record from DDB.
|
25
|
+
*/
|
26
|
+
export interface ApwSettings {
|
27
|
+
mainGraphqlFunctionArn: string;
|
28
|
+
cmsGraphqlFunctionArn: string;
|
29
|
+
eventRuleName: string;
|
30
|
+
eventTargetId: string;
|
31
|
+
}
|
32
|
+
export declare const getApwSettings: () => Promise<ApwSettings>;
|
33
|
+
export {};
|
@@ -0,0 +1,168 @@
|
|
1
|
+
"use strict";
|
2
|
+
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
+
|
5
|
+
Object.defineProperty(exports, "__esModule", {
|
6
|
+
value: true
|
7
|
+
});
|
8
|
+
exports.shouldRestoreDatetime = exports.moveDateTimeToNextCentury = exports.moveDateTimeToCurrentCentury = exports.isDateTimeInNextCentury = exports.getIsoStringTillMinutes = exports.getApwSettings = exports.encodeToken = exports.documentClient = exports.decodeToken = exports.dateTimeToCronExpression = exports.basePlugins = exports.TOKEN_PREFIX = void 0;
|
9
|
+
|
10
|
+
var _dayjs = _interopRequireDefault(require("dayjs"));
|
11
|
+
|
12
|
+
var _utc = _interopRequireDefault(require("dayjs/plugin/utc"));
|
13
|
+
|
14
|
+
var _dynamodb = require("aws-sdk/clients/dynamodb");
|
15
|
+
|
16
|
+
var _handlerDb = _interopRequireDefault(require("@webiny/handler-db"));
|
17
|
+
|
18
|
+
var _dbDynamodb = require("@webiny/db-dynamodb");
|
19
|
+
|
20
|
+
var _plugins = _interopRequireDefault(require("@webiny/db-dynamodb/plugins"));
|
21
|
+
|
22
|
+
var _handlerLogs = _interopRequireDefault(require("@webiny/handler-logs"));
|
23
|
+
|
24
|
+
var _types = require("../types");
|
25
|
+
|
26
|
+
/**
|
27
|
+
* https://day.js.org/docs/en/plugin/utc
|
28
|
+
*/
|
29
|
+
_dayjs.default.extend(_utc.default);
|
30
|
+
|
31
|
+
const TIME_SEPARATOR = ":";
|
32
|
+
const ELAPSED_CRON_EXPRESSION = "* * * * ? 2000";
|
33
|
+
|
34
|
+
const getIsoStringTillMinutes = datetime => {
|
35
|
+
/**
|
36
|
+
* Validate datetime.
|
37
|
+
*/
|
38
|
+
if (isNaN(Date.parse(datetime))) {
|
39
|
+
return datetime;
|
40
|
+
} // input = "2022-03-08T05:41:13.230Z"
|
41
|
+
// output = "2022-03-08T05:41"
|
42
|
+
|
43
|
+
|
44
|
+
return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));
|
45
|
+
};
|
46
|
+
|
47
|
+
exports.getIsoStringTillMinutes = getIsoStringTillMinutes;
|
48
|
+
|
49
|
+
const dateTimeToCronExpression = datetime => {
|
50
|
+
if (!datetime) {
|
51
|
+
return ELAPSED_CRON_EXPRESSION;
|
52
|
+
}
|
53
|
+
/**
|
54
|
+
* You can't specify the Day-of-month and Day-of-week fields in the same cron expression.
|
55
|
+
* If you specify a value (or a *) in one of the fields, you must use a ? (question mark) in the other.
|
56
|
+
*
|
57
|
+
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
|
58
|
+
*/
|
59
|
+
|
60
|
+
|
61
|
+
const dayOfWeek = "?";
|
62
|
+
return _dayjs.default.utc(datetime).format(`mm H D M [${dayOfWeek}] YYYY`);
|
63
|
+
};
|
64
|
+
|
65
|
+
exports.dateTimeToCronExpression = dateTimeToCronExpression;
|
66
|
+
|
67
|
+
const moveDateTimeToNextCentury = datetime => {
|
68
|
+
return _dayjs.default.utc(datetime).add(100, "year").toISOString();
|
69
|
+
};
|
70
|
+
|
71
|
+
exports.moveDateTimeToNextCentury = moveDateTimeToNextCentury;
|
72
|
+
|
73
|
+
const moveDateTimeToCurrentCentury = datetime => {
|
74
|
+
return _dayjs.default.utc(datetime).subtract(100, "year").toISOString();
|
75
|
+
};
|
76
|
+
|
77
|
+
exports.moveDateTimeToCurrentCentury = moveDateTimeToCurrentCentury;
|
78
|
+
|
79
|
+
const isDateTimeInNextCentury = datetime => {
|
80
|
+
return _dayjs.default.utc(datetime).isAfter("2100-01-01", "year");
|
81
|
+
};
|
82
|
+
|
83
|
+
exports.isDateTimeInNextCentury = isDateTimeInNextCentury;
|
84
|
+
|
85
|
+
const shouldRestoreDatetime = ({
|
86
|
+
invocationType,
|
87
|
+
datetime
|
88
|
+
}) => {
|
89
|
+
/**
|
90
|
+
* "invocationType" will not be SCHEDULED when the lambda is called from Main GQL handler.
|
91
|
+
*
|
92
|
+
* Which means a new content is scheduled for "publish"/"unpublish" therefore, we need to restore the previously
|
93
|
+
* scheduled action if it has not been executed already.
|
94
|
+
*/
|
95
|
+
const selfInvoked = invocationType === _types.InvocationTypes.SCHEDULED;
|
96
|
+
|
97
|
+
const today = _dayjs.default.utc();
|
98
|
+
|
99
|
+
const isExecutionPending = _dayjs.default.utc(datetime).isAfter(today);
|
100
|
+
|
101
|
+
return !selfInvoked && isExecutionPending;
|
102
|
+
};
|
103
|
+
|
104
|
+
exports.shouldRestoreDatetime = shouldRestoreDatetime;
|
105
|
+
|
106
|
+
const encodeToken = ({
|
107
|
+
id,
|
108
|
+
tenant,
|
109
|
+
locale
|
110
|
+
}) => {
|
111
|
+
return `${TOKEN_PREFIX}${id}__${tenant}__${locale}`;
|
112
|
+
};
|
113
|
+
|
114
|
+
exports.encodeToken = encodeToken;
|
115
|
+
const TOKEN_PREFIX = "apw-";
|
116
|
+
exports.TOKEN_PREFIX = TOKEN_PREFIX;
|
117
|
+
|
118
|
+
const decodeToken = token => {
|
119
|
+
const auth = token.slice(TOKEN_PREFIX.length);
|
120
|
+
const [id, tenant, locale] = auth.split("__");
|
121
|
+
return {
|
122
|
+
id,
|
123
|
+
tenant,
|
124
|
+
locale
|
125
|
+
};
|
126
|
+
};
|
127
|
+
|
128
|
+
exports.decodeToken = decodeToken;
|
129
|
+
const documentClient = new _dynamodb.DocumentClient({
|
130
|
+
convertEmptyValues: true,
|
131
|
+
region: process.env.AWS_REGION
|
132
|
+
});
|
133
|
+
exports.documentClient = documentClient;
|
134
|
+
|
135
|
+
const basePlugins = () => [(0, _plugins.default)(), (0, _handlerLogs.default)(), (0, _handlerDb.default)({
|
136
|
+
table: process.env.DB_TABLE,
|
137
|
+
driver: new _dbDynamodb.DynamoDbDriver({
|
138
|
+
documentClient
|
139
|
+
})
|
140
|
+
})];
|
141
|
+
/**
|
142
|
+
* Get APW settings record from DDB.
|
143
|
+
*/
|
144
|
+
|
145
|
+
|
146
|
+
exports.basePlugins = basePlugins;
|
147
|
+
|
148
|
+
const getApwSettings = async () => {
|
149
|
+
const variant = process.env.STAGED_ROLLOUTS_VARIANT;
|
150
|
+
const params = {
|
151
|
+
TableName: process.env.DB_TABLE,
|
152
|
+
Key: {
|
153
|
+
PK: `APW#SETTINGS`,
|
154
|
+
SK: variant || "default"
|
155
|
+
}
|
156
|
+
};
|
157
|
+
const {
|
158
|
+
Item
|
159
|
+
} = await documentClient.get(params).promise();
|
160
|
+
return {
|
161
|
+
mainGraphqlFunctionArn: Item ? Item["mainGraphqlFunctionArn"] : "mainGraphqlFunctionArn",
|
162
|
+
cmsGraphqlFunctionArn: Item ? Item["cmsGraphqlFunctionArn"] : "cmsGraphqlFunctionArn",
|
163
|
+
eventRuleName: Item ? Item["eventRuleName"] : "eventRuleName",
|
164
|
+
eventTargetId: Item ? Item["eventTargetId"] : "eventTargetId"
|
165
|
+
};
|
166
|
+
};
|
167
|
+
|
168
|
+
exports.getApwSettings = getApwSettings;
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"names":["dayjs","extend","utc","TIME_SEPARATOR","ELAPSED_CRON_EXPRESSION","getIsoStringTillMinutes","datetime","isNaN","Date","parse","slice","lastIndexOf","dateTimeToCronExpression","dayOfWeek","format","moveDateTimeToNextCentury","add","toISOString","moveDateTimeToCurrentCentury","subtract","isDateTimeInNextCentury","isAfter","shouldRestoreDatetime","invocationType","selfInvoked","InvocationTypes","SCHEDULED","today","isExecutionPending","encodeToken","id","tenant","locale","TOKEN_PREFIX","decodeToken","token","auth","length","split","documentClient","DocumentClient","convertEmptyValues","region","process","env","AWS_REGION","basePlugins","dynamoDbPlugins","logsPlugins","dbPlugins","table","DB_TABLE","driver","DynamoDbDriver","getApwSettings","variant","STAGED_ROLLOUTS_VARIANT","params","TableName","Key","PK","SK","Item","get","promise","mainGraphqlFunctionArn","cmsGraphqlFunctionArn","eventRuleName","eventTargetId"],"sources":["utils.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\nimport { DocumentClient } from \"aws-sdk/clients/dynamodb\";\nimport dbPlugins from \"@webiny/handler-db\";\nimport { DynamoDbDriver } from \"@webiny/db-dynamodb\";\nimport dynamoDbPlugins from \"@webiny/db-dynamodb/plugins\";\nimport logsPlugins from \"@webiny/handler-logs\";\nimport { InvocationTypes } from \"~/scheduler/types\";\n\n/**\n * https://day.js.org/docs/en/plugin/utc\n */\ndayjs.extend(utc);\n\nconst TIME_SEPARATOR = \":\";\nconst ELAPSED_CRON_EXPRESSION = \"* * * * ? 2000\";\n\nexport const getIsoStringTillMinutes = (datetime: string): string => {\n /**\n * Validate datetime.\n */\n if (isNaN(Date.parse(datetime))) {\n return datetime;\n }\n // input = \"2022-03-08T05:41:13.230Z\"\n // output = \"2022-03-08T05:41\"\n return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));\n};\n\nexport const dateTimeToCronExpression = (datetime: string): string => {\n if (!datetime) {\n return ELAPSED_CRON_EXPRESSION;\n }\n /**\n * You can't specify the Day-of-month and Day-of-week fields in the same cron expression.\n * If you specify a value (or a *) in one of the fields, you must use a ? (question mark) in the other.\n *\n * https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html\n */\n const dayOfWeek = \"?\";\n\n return dayjs.utc(datetime).format(`mm H D M [${dayOfWeek}] YYYY`);\n};\n\nexport const moveDateTimeToNextCentury = (datetime: string): string => {\n return dayjs.utc(datetime).add(100, \"year\").toISOString();\n};\n\nexport const moveDateTimeToCurrentCentury = (datetime: string): string => {\n return dayjs.utc(datetime).subtract(100, \"year\").toISOString();\n};\n\nexport const isDateTimeInNextCentury = (datetime: string): boolean => {\n return dayjs.utc(datetime).isAfter(\"2100-01-01\", \"year\");\n};\n\ninterface ShouldRestoreDatetimeParams {\n invocationType?: InvocationTypes;\n datetime: string;\n}\n\nexport const shouldRestoreDatetime = ({\n invocationType,\n datetime\n}: ShouldRestoreDatetimeParams): boolean => {\n /**\n * \"invocationType\" will not be SCHEDULED when the lambda is called from Main GQL handler.\n *\n * Which means a new content is scheduled for \"publish\"/\"unpublish\" therefore, we need to restore the previously\n * scheduled action if it has not been executed already.\n */\n const selfInvoked = invocationType === InvocationTypes.SCHEDULED;\n\n const today = dayjs.utc();\n const isExecutionPending = dayjs.utc(datetime).isAfter(today);\n\n return !selfInvoked && isExecutionPending;\n};\n\ninterface EncodeTokenParams {\n id: string;\n tenant: string;\n locale: string;\n}\n\nexport const encodeToken = ({ id, tenant, locale }: EncodeTokenParams) => {\n return `${TOKEN_PREFIX}${id}__${tenant}__${locale}`;\n};\n\nexport const TOKEN_PREFIX = \"apw-\";\n\nexport const decodeToken = (token: string): Partial<EncodeTokenParams> => {\n const auth = token.slice(TOKEN_PREFIX.length);\n const [id, tenant, locale] = auth.split(\"__\");\n\n return {\n id,\n tenant,\n locale\n };\n};\n\nexport const documentClient = new DocumentClient({\n convertEmptyValues: true,\n region: process.env.AWS_REGION\n});\n\nexport const basePlugins = () => [\n dynamoDbPlugins(),\n logsPlugins(),\n dbPlugins({\n table: process.env.DB_TABLE,\n driver: new DynamoDbDriver({\n documentClient\n })\n })\n];\n\n/**\n * Get APW settings record from DDB.\n */\nexport interface ApwSettings {\n mainGraphqlFunctionArn: string;\n cmsGraphqlFunctionArn: string;\n eventRuleName: string;\n eventTargetId: string;\n}\n\nexport const getApwSettings = async (): Promise<ApwSettings> => {\n const variant = process.env.STAGED_ROLLOUTS_VARIANT;\n\n const params = {\n TableName: process.env.DB_TABLE as string,\n Key: {\n PK: `APW#SETTINGS`,\n SK: variant || \"default\"\n }\n };\n\n const { Item } = await documentClient.get(params).promise();\n\n return {\n mainGraphqlFunctionArn: Item ? Item[\"mainGraphqlFunctionArn\"] : \"mainGraphqlFunctionArn\",\n cmsGraphqlFunctionArn: Item ? Item[\"cmsGraphqlFunctionArn\"] : \"cmsGraphqlFunctionArn\",\n eventRuleName: Item ? Item[\"eventRuleName\"] : \"eventRuleName\",\n eventTargetId: Item ? Item[\"eventTargetId\"] : \"eventTargetId\"\n };\n};\n"],"mappings":";;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;AACA;AACA;AACAA,cAAA,CAA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