-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathplugin.ts
More file actions
336 lines (305 loc) · 13.3 KB
/
Copy pathplugin.ts
File metadata and controls
336 lines (305 loc) · 13.3 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/**
* Copyright 2026 GitProxy Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Request } from 'express';
import { loadPlugin, resolvePlugin } from 'load-plugin';
import Module from 'node:module';
import { Action } from './proxy/actions';
import { handleErrorAndLog } from './utils/errors';
import { PullPhase, PushChainName, PushPhase } from './proxy/processors/types';
/* eslint-disable @typescript-eslint/no-unused-expressions */
('use strict');
/**
* Checks if the given object or any of its prototypes has the 'isGitProxyPlugin' property set to true.
* @param {Object} obj - The object to check.
* @param {string} propertyName - The property name to check for. Default is 'isGitProxyPlugin'.
* @return {boolean} - True if the object or any of its prototypes has the 'isGitProxyPlugin' property set to true, false otherwise.
*/
function isCompatiblePlugin(obj: any, propertyName: string = 'isGitProxyPlugin'): boolean {
// loop through the prototype chain to check if the object is a ProxyPlugin
// valid plugin objects will have the appropriate property set to true
// if the prototype chain is exhausted, return false
while (obj != null) {
if (
Object.prototype.hasOwnProperty.call(obj, propertyName) &&
obj.isGitProxyPlugin &&
Object.keys(obj).includes('exec')
) {
return true;
}
obj = Object.getPrototypeOf(obj);
}
return false;
}
interface PluginTypeResult {
pushAction: PushActionPlugin[];
pullAction: PullActionPlugin[];
}
/**
* Registers and loads plugins used by git-proxy
*/
class PluginLoader {
targets: string[];
pushPlugins: PushActionPlugin[];
pullPlugins: PullActionPlugin[];
constructor(targets: string[]) {
this.targets = targets;
this.pushPlugins = [];
this.pullPlugins = [];
if (this.targets.length === 0) {
console.log('No plugins configured'); // TODO: log.debug()
}
}
/**
* Load all plugins specified in the `targets` property. This method must complete before a PluginLoader instance
* can be used to retrieve plugins.
* @return {Promise<void>} A Promise that resolves when all plugins have been loaded.
*/
async load(): Promise<void> {
try {
const modulePromises = this.targets.map((target) =>
this._loadPluginModule(target).catch((error) => {
console.error(`Failed to load plugin: ${error}`); // TODO: log.error()
return Promise.reject(error); // Or return an error object to handle it later
}),
);
const moduleResults = await Promise.allSettled(modulePromises);
const loadedModules = moduleResults
.filter(
(result): result is PromiseFulfilledResult<Module> =>
result.status === 'fulfilled' && result.value !== null,
)
.map((result) => result.value);
console.log(`Found ${loadedModules.length} plugin modules`); // TODO: log.debug()
const pluginTypeResultPromises = loadedModules.map((mod) =>
this._getPluginObjects(mod).catch((error) => {
console.error(`Failed to cast plugin objects: ${error}`); // TODO: log.error()
return Promise.reject(error); // Or return an error object to handle it later
}),
);
const settledPluginTypeResults = await Promise.allSettled(pluginTypeResultPromises);
/**
* @type {PluginTypeResult[]} List of resolved PluginTypeResult objects
*/
const pluginTypeResults = settledPluginTypeResults
.filter(
(result): result is PromiseFulfilledResult<PluginTypeResult> =>
result.status === 'fulfilled' && result.value !== null,
)
.map((result) => result.value);
for (const result of pluginTypeResults) {
this.pushPlugins.push(...result.pushAction);
this.pullPlugins.push(...result.pullAction);
}
const combinedPlugins = [...this.pushPlugins, ...this.pullPlugins];
combinedPlugins.forEach((plugin) => {
console.log(`Loaded plugin: ${plugin.constructor.name}`);
});
} catch (error: unknown) {
handleErrorAndLog(error, 'Error loading plugins');
}
}
/**
* Resolve & load a Node module from either a given specifier (file path, import specifier or package name) using load-plugin.
* @param {string} target The module specifier to load
* @return {Promise<unknown>} A resolved & loaded Module
*/
private async _loadPluginModule(target: string): Promise<unknown> {
const resolvedModuleFile = await resolvePlugin(target);
return loadPlugin(resolvedModuleFile);
}
/**
* Checks for known compatible plugin objects in a Module and returns them classified by their type.
* @param {Module} pluginModule The module to extract plugins from
* @return {Promise<PluginTypeResult>} An object containing the loaded plugins classified by their type.
*/
private async _getPluginObjects(pluginModule: any): Promise<PluginTypeResult> {
const plugins: PluginTypeResult = {
pushAction: [],
pullAction: [],
};
function handlePlugin(potentialModule: any) {
if (isCompatiblePlugin(potentialModule, 'isGitProxyPushActionPlugin')) {
console.log('found push plugin', potentialModule.constructor.name);
plugins.pushAction.push(potentialModule);
} else if (isCompatiblePlugin(potentialModule, 'isGitProxyPullActionPlugin')) {
console.log('found pull plugin', potentialModule.constructor.name);
plugins.pullAction.push(potentialModule);
} else {
console.error(
`Error: Object ${potentialModule.constructor.name} does not seem to be a compatible plugin type`,
);
}
}
// handles the default export case
// `module.exports = new ProxyPlugin()` in CJS or `exports default new ProxyPlugin()` in ESM
// the "module" is a single object that could be a plugin
if (isCompatiblePlugin(pluginModule)) {
handlePlugin(pluginModule);
} else {
// handle the typical case of a module which exports multiple objects
// module.exports = { x, y } (CJS) or multiple `export ...` statements (ESM)
for (const key of Object.keys(pluginModule)) {
if (isCompatiblePlugin(pluginModule[key])) {
handlePlugin(pluginModule[key]);
}
}
}
return plugins;
}
}
/**
* Parent class for all GitProxy plugins. New plugin types must inherit from
* ProxyPlugin to be loaded by PluginLoader.
*/
class ProxyPlugin {
isGitProxyPlugin: boolean;
constructor() {
this.isGitProxyPlugin = true;
}
}
/**
* Options for all ActionPlugin instances.
* @property {boolean} isCollectible - If true, the plugin will not stop the chain if it fails. Errors will be collected
* and reported at the end of the chain. Useful for plugins that are not critical to the success of the operation.
* @property {string} displayName - The name of the plugin which is used for user-facing progress reporting. Optional.
* @property {PushPhase | PullPhase} phase - The phase of the action chain where the plugin will be executed. Optional.
*/
interface ActionPluginOptions {
readonly isCollectible?: boolean;
readonly displayName?: string;
readonly phase?: PushPhase | PullPhase;
}
/**
* Options for PushActionPlugin instances, extended from {ActionPluginOptions}.
* @property {PushPhase} phase - The phase of the *push* action chain where the plugin will be executed. Defaults to {PushPhase.AFTER_PERMISSIONS}.
* @property {PushChainName[]} chains - The push operations where the plugin will be executed. Optional, defaults to all push operations.
*/
interface PushPluginOptions extends ActionPluginOptions {
readonly phase?: PushPhase;
readonly chains?: PushChainName[];
}
/**
* Options for PullActionPlugin instances, extended from {ActionPluginOptions}.
* @property {PullPhase} phase - The phase of the *pull* action chain where the plugin will be executed. Defaults to {PullPhase.AFTER_AUTHORISATION}.
*/
interface PullPluginOptions extends ActionPluginOptions {
readonly phase?: PullPhase;
}
/**
* Base class for all action plugins (executed as part of the action chain for
* `git push` or `git pull` operations).
*/
export abstract class ActionPlugin extends ProxyPlugin {
exec: (req: Request, action: Action) => Promise<Action>;
readonly isCollectible: boolean;
readonly displayName?: string;
readonly phase: PushPhase | PullPhase;
/**
* Parent constructor for all ActionPlugin instances. Do not use this constructor directly.
*/
constructor(
exec: (req: Request, action: Action) => Promise<Action>,
options: ActionPluginOptions & { phase: PushPhase | PullPhase },
) {
super();
this.exec = exec;
this.isCollectible = options.isCollectible ?? false;
this.displayName = options.displayName;
this.phase = options.phase;
}
}
/**
* A plugin which executes a function when receiving a git push request.
*/
class PushActionPlugin extends ActionPlugin {
isGitProxyPushActionPlugin = true;
declare readonly phase: PushPhase;
declare readonly chains?: PushChainName[];
/**
* Wrapper class which contains at least one function executed as part of the action chain for git push operations.
* The function must be called `exec` and take in two parameters: an Express Request (req) and the current Action
* executed in the chain (action). This function should return a Promise that resolves to an Action.
*
* Optionally, child classes which extend this can simply define the `exec` function as their own property.
* This is the preferred implementation when a custom plugin (subclass) has its own state or additional methods
* that are required.
*
* @param {function} exec - A function that:
* - Takes in an Express Request object as the first parameter (`req`).
* - Takes in an Action object as the second parameter (`action`).
* - Returns a Promise that resolves to an Action.
*
* @param {PushPluginOptions} options - An object containing the following properties:
* - {boolean} isCollectible - If true, the plugin will not stop the chain if it fails. Errors will be collected
* and reported at the end of the chain. Useful for plugins that are not critical to the success of the operation.
* - {string} displayName - The name of the plugin which is used for user-facing progress reporting. Optional.
* - {PushPhase} phase - The phase of the *push* action chain where the plugin will be executed. Optional, defaults to {PushPhase.AFTER_PERMISSIONS}.
* - {PushChainName[]} chains - The push operations where the plugin will be executed. Optional, defaults to all push operations.
*/
constructor(
exec: (req: Request, action: Action) => Promise<Action>,
options: PushPluginOptions = {},
) {
super(exec, { ...options, phase: options.phase ?? PushPhase.AFTER_PERMISSIONS });
this.isGitProxyPushActionPlugin = true;
this.chains = options.chains;
}
}
/**
* A plugin which executes a function when receiving a git fetch request.
*/
class PullActionPlugin extends ActionPlugin {
isGitProxyPullActionPlugin = true;
declare readonly phase: PullPhase;
/**
* Wrapper class which contains at least one function executed as part of the action chain for git pull operations.
* The function must be called `exec` and take in two parameters: an Express Request (req) and the current Action
* executed in the chain (action). This function should return a Promise that resolves to an Action.
*
* Optionally, child classes which extend this can simply define the `exec` function as their own property.
* This is the preferred implementation when a custom plugin (subclass) has its own state or additional methods
* that are required.
*
* @param {function} exec - A function that:
* - Takes in an Express Request object as the first parameter (`req`).
* - Takes in an Action object as the second parameter (`action`).
* - Returns a Promise that resolves to an Action.
*
* @param {PushPluginOptions} options - An object containing the following properties:
* - {boolean} isCollectible - If true, the plugin will not stop the chain if it fails. Errors will be collected
* and reported at the end of the chain. Useful for plugins that are not critical to the success of the operation.
* - {string} displayName - The name of the plugin which is used for user-facing progress reporting. Optional.
* - {PullPhase} phase - The phase of the *pull* action chain where the plugin will be executed. Optional, defaults to {PullPhase.AFTER_AUTHORISATION}.
*/
constructor(
exec: (req: Request, action: Action) => Promise<Action>,
options: PullPluginOptions = {},
) {
super(exec, { ...options, phase: options.phase ?? PullPhase.AFTER_AUTHORISATION });
this.isGitProxyPullActionPlugin = true;
}
}
export {
PluginLoader,
PushActionPlugin,
PullActionPlugin,
isCompatiblePlugin,
PushPhase,
PullPhase,
PushChainName,
PushPluginOptions,
PullPluginOptions,
};