-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin-manager.ts
More file actions
251 lines (202 loc) · 8.69 KB
/
Copy pathplugin-manager.ts
File metadata and controls
251 lines (202 loc) · 8.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import {
ApplyNoteRequestData,
ImportResponseData, ResourceDefinition,
ResourceJson,
ValidateResponseData,
} from '@codifycli/schemas';
import { InternalError, PluginError } from '../common/errors.js';
import { config } from '../config.js';
import { ApplyNote } from '../entities/apply-note.js';
import { ApplyResult, createApplyResult } from '../entities/apply-result.js';
import { Plan, ResourcePlan } from '../entities/plan.js';
import { Project } from '../entities/project.js';
import { ResourceConfig } from '../entities/resource-config.js';
import { ResourceInfo } from '../entities/resource-info.js';
import { Event, SubProcessName, SubprocessFinishStatus, ctx } from '../events/context.js';
import { groupBy } from '../utils/index.js';
import { registerKillListeners } from '../utils/register-kill-listeners.js';
import { Plugin } from './plugin.js';
import { PluginResolver } from './resolver.js';
import { VerbosityLevel } from '../utils/verbosity-level.js';
type PluginName = string;
type ResourceTypeId = string;
export type ResourceDefinitionMap = Map<ResourceTypeId, ResourceDefinition>;
const DEFAULT_PLUGINS = {
'default': 'latest',
}
const BETA_DEFAULT_PLUGINS = {
'default': 'beta',
}
export class PluginManager {
private plugins = new Map<PluginName, Plugin>()
private resourceToPluginMapping = new Map<string, string>()
private pluginToResourceMapping = new Map<string, string[]>()
async initialize(project: Project | null, secureMode = false, verbosityLevel = 0): Promise<ResourceDefinitionMap> {
const plugins = await this.resolvePlugins(project);
for (const plugin of plugins) {
this.plugins.set(plugin.name, plugin)
}
registerKillListeners(() => {
for (const plugin of plugins) {
plugin.kill()
}
});
return this.initializePlugins(plugins, secureMode, verbosityLevel);
}
async validate(project: Project): Promise<ValidateResponseData[]> {
const { resourceConfigs } = project;
const pluginGroupedResourceConfigs = groupBy(
resourceConfigs,
(item) => this.resourceToPluginMapping.get(item.type)!
);
return Promise.all(
Object.entries(pluginGroupedResourceConfigs).map(([pluginName, configs]) =>
this.plugins.get(pluginName)!.validate(configs)
)
);
}
async getMultipleResourceInfo(typeIds: string[]): Promise<ResourceInfo[]> {
return Promise.all(typeIds.map((type) => this.getResourceInfo(type)))
}
async getResourceInfo(type: string): Promise<ResourceInfo> {
const pluginName = this.resourceToPluginMapping.get(type);
if (!pluginName) {
throw new Error(`Unable to find plugin for resource: ${type}`);
}
const plugin = this.plugins.get(pluginName)
if (!plugin) {
throw new Error(`Unable to find plugin for resource ${type}`);
}
const result = await plugin.getResourceInfo(type);
return ResourceInfo.fromResponseData(result);
}
async match(resource: ResourceConfig, array: ResourceConfig[]): Promise<ResourceConfig | null> {
const pluginName = this.resourceToPluginMapping.get(resource.type);
if (!pluginName) {
throw new Error(`Unable to find plugin for resource: ${resource.type}`);
}
const plugin = this.plugins.get(pluginName)
if (!plugin) {
throw new Error(`Unable to find plugin for resource ${resource.type}`);
}
const { match } = await plugin.match(resource, array);
if (!match) {
return null;
}
return ResourceConfig.fromJson(match);
}
async importResource(config: ResourceJson, autoImportAll = false): Promise<ImportResponseData> {
const pluginName = this.resourceToPluginMapping.get(config.core.type);
if (!pluginName) {
throw new Error(`Unable to find plugin for resource: ${config.core.type}`);
}
const plugin = this.plugins.get(pluginName)
if (!plugin) {
throw new Error(`Unable to find plugin for resource ${config.core.type}`);
}
return plugin.import(config, autoImportAll);
}
async plan(project: Project): Promise<Plan> {
const result = new Array<ResourcePlan>();
await Promise.all(
project.evaluationOrder!.map(async (id) => {
const planRequest = project.getPlanRequest(id)!;
const pluginName = this.resourceToPluginMapping.get(planRequest.core.type);
if (!pluginName) {
throw new InternalError(`Unable to determine plugin for validated resource: ${planRequest.core.type}`);
}
const planResult = await this.plugins.get(pluginName)!.plan(planRequest);
result.push(planResult);
})
)
return new Plan(result, project);
}
async apply(project: Project, plan: Plan): Promise<ApplyResult> {
const collectedErrors: PluginError[] = [];
const skippedIds = new Set<string>();
const succeededPlans: ResourcePlan[] = [];
const collectedNotes: ApplyNote[] = [];
const noteListener = (_pluginName: string, data: ApplyNoteRequestData) => {
collectedNotes.push({ message: data.message, resourceType: data.resourceType });
};
ctx.on(Event.APPLY_NOTE_REQUEST, noteListener);
for (const id of project.evaluationOrder ?? []) {
if (skippedIds.has(id)) {
ctx.subprocessStarted(SubProcessName.APPLYING_RESOURCE, id);
ctx.subprocessFinished(SubProcessName.APPLYING_RESOURCE, id, SubprocessFinishStatus.SKIPPED);
continue;
}
ctx.subprocessStarted(SubProcessName.APPLYING_RESOURCE, id);
const resourcePlan = plan.getResourcePlan(id);
if (!resourcePlan) {
throw new InternalError(`Could not find resourcePlan: ${id}`)
}
const { resourceType } = resourcePlan;
const pluginName = this.resourceToPluginMapping.get(resourceType);
if (!pluginName) {
throw new InternalError(`Unable to determine plugin for apply: ${resourceType}`);
}
try {
await this.plugins.get(pluginName)!.apply(resourcePlan);
succeededPlans.push(resourcePlan);
ctx.subprocessFinished(SubProcessName.APPLYING_RESOURCE, resourcePlan.id, SubprocessFinishStatus.SUCCESS);
} catch (err) {
if (err instanceof PluginError) {
collectedErrors.push(err);
ctx.subprocessFinished(SubProcessName.APPLYING_RESOURCE, resourcePlan.id, SubprocessFinishStatus.FAILED);
const dependents = plan.computeTransitiveDependents(id);
for (const depId of dependents) skippedIds.add(depId);
} else {
throw err;
}
}
}
ctx.emitter.removeListener(Event.APPLY_NOTE_REQUEST, noteListener);
return createApplyResult(succeededPlans, collectedErrors, skippedIds, collectedNotes);
}
async setVerbosityLevel(verbosityLevel: number): Promise<void> {
VerbosityLevel.set(verbosityLevel);
for (const plugin of this.plugins.values()) {
await plugin.setVerbosityLevel(verbosityLevel);
}
}
private async resolvePlugins(project: Project | null): Promise<Plugin[]> {
const { isBeta } = config;
// We handle beta plugins auto-magically currently. It will check that the version "beta" does not exist locally and
// download every time (the intended behavior).
const pluginDefinitions: Record<string, string> = {
...isBeta ? BETA_DEFAULT_PLUGINS : DEFAULT_PLUGINS,
...project?.projectConfig?.plugins,
};
return PluginResolver.resolveAll(pluginDefinitions);
}
private async initializePlugins(plugins: Plugin[], secureMode: boolean, verbosityLevel: number): Promise<Map<string, ResourceDefinition>> {
const responses = await Promise.all(
plugins.map(async (p) => {
const initializeResult = await p.initialize(secureMode, verbosityLevel);
return [p.name, initializeResult.resourceDefinitions] as const
})
);
const resourceMap = new Map<string, ResourceDefinition>();
for (const [pluginName, definitions] of responses) {
for (const definition of definitions) {
// Build resource to plugin mapping
if (this.resourceToPluginMapping.has(definition.type)) {
throw new Error(`Duplicated types between plugin ${this.resourceToPluginMapping.get(definition.type)} and ${pluginName}`)
}
this.resourceToPluginMapping.set(definition.type, pluginName);
// Build plugin to resource mapping
if (!this.pluginToResourceMapping.has(pluginName)) {
this.pluginToResourceMapping.set(pluginName, []);
}
this.pluginToResourceMapping.get(pluginName)!.push(definition.type);
// Build resource dependency map
if (resourceMap.has(definition.type)) {
throw new Error(`Duplicated types between plugins ${this.resourceToPluginMapping.get(definition.type)} and ${pluginName}`);
}
resourceMap.set(definition.type, definition)
}
}
return resourceMap;
}
}