forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromoter.ts
More file actions
397 lines (361 loc) · 11.1 KB
/
Copy pathpromoter.ts
File metadata and controls
397 lines (361 loc) · 11.1 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
* Environment Promotion Module
*
* Manages promotion of deployments across environments (dev -> staging -> production)
* with validation, rollback capabilities, and audit logging.
* Orchestrates the blue-green deployment state machine from {@link ../deploy}.
*
* @module deployment/promoter
*/
import { Environment, loadEnvironmentConfig } from '../config/environment';
import { ValidationResult, validateDeploymentReadiness, performHealthCheck } from './validator';
import { auditService } from '../audit/service';
import { recordPromotion, recordRollback, fetchHistory } from './historyStore';
import { randomUUID } from 'crypto';
import { switchToGreen, rollback as blueGreenRollback, getStatus } from '../deploy';
export interface PromotionRequest {
/** Source environment */
from: Environment;
/** Target environment */
to: Environment;
/** Version/tag to promote */
version: string;
/** User initiating promotion */
initiatedBy: string;
/** Timestamp of promotion request */
timestamp: Date;
}
export interface PromotionResult {
/** Whether promotion was successful */
success: boolean;
/** Promotion request details */
request: PromotionRequest;
/** Validation results */
validation: ValidationResult;
/** Error message if failed */
error?: string;
/** Promotion ID for tracking */
promotionId: string;
}
export interface RollbackRequest {
/** Environment to rollback */
environment: Environment;
/** Version to rollback to */
targetVersion: string;
/** Reason for rollback */
reason: string;
/** User initiating rollback */
initiatedBy: string;
}
export interface RollbackResult {
/** Whether rollback was successful */
success: boolean;
/** Rollback request details */
request: RollbackRequest;
/** Error message if failed */
error?: string;
/** Rollback ID for tracking */
rollbackId: string;
}
/**
* Validates promotion path between environments
* @param {Environment} from - Source environment
* @param {Environment} to - Target environment
* @returns {ValidationResult} Validation result
*/
export function validatePromotionPath(from: Environment, to: Environment): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Define valid promotion paths
const validPaths: Record<Environment, Environment[]> = {
development: ['staging'],
staging: ['production'],
production: [],
test: [],
};
if (!validPaths[from].includes(to)) {
errors.push(
`Invalid promotion path: ${from} -> ${to}. ` +
`Valid paths from ${from}: ${validPaths[from].join(', ') || 'none'}`
);
}
if (to === 'production' && from === 'development') {
warnings.push('Direct promotion from development to production is not recommended');
}
return {
valid: errors.length === 0,
errors,
warnings,
};
}
/**
* Generates a unique promotion ID
* @returns {string} Unique promotion identifier
*/
function generatePromotionId(): string {
return `promo-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Generates a unique rollback ID
* @returns {string} Unique rollback identifier
*/
function generateRollbackId(): string {
return `rollback-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Rolls back a deployment to a previous version
*
* Uses the blue-green {@link ../deploy.ts rollback} state machine to revert
* the active deployment colour, then persists the rollback record and emits
* an audit event.
*
* @param {RollbackRequest} request - Rollback request details
* @returns {Promise<RollbackResult>} Rollback result
*/
export async function rollbackDeployment(
request: RollbackRequest
): Promise<RollbackResult> {
const rollbackId = generateRollbackId();
if (!request.targetVersion) {
return {
success: false,
request,
error: 'Target version is required for rollback',
rollbackId,
};
}
if (request.environment === 'development') {
return {
success: false,
request,
error: 'Rollback not supported for development environment',
rollbackId,
};
}
try {
await blueGreenRollback();
recordRollback({
id: randomUUID(),
environment: request.environment,
targetVersion: request.targetVersion,
rollbackId,
initiatedBy: request.initiatedBy,
timestamp: new Date().toISOString(),
status: 'SUCCESS',
});
auditService.log({
action: 'DEPLOYMENT_ROLLED_BACK',
severity: 'WARNING',
actor: request.initiatedBy,
resource: 'deployment',
resourceId: request.targetVersion,
metadata: { environment: request.environment, rollbackId },
});
return {
success: true,
request,
rollbackId,
};
} catch (err: any) {
recordRollback({
id: randomUUID(),
environment: request.environment,
targetVersion: request.targetVersion,
rollbackId,
initiatedBy: request.initiatedBy,
timestamp: new Date().toISOString(),
status: 'FAILURE',
error: err.message,
});
auditService.log({
action: 'DEPLOYMENT_ROLLED_BACK',
severity: 'CRITICAL',
actor: request.initiatedBy,
resource: 'deployment',
resourceId: request.targetVersion,
metadata: { environment: request.environment, rollbackId, error: err.message },
});
return {
success: false,
request,
error: err.message,
rollbackId,
};
}
}
/**
* Promotes a deployment from one environment to another
*
* Orchestrates the full promotion lifecycle:
* 1. Validates the promotion path (dev→staging, staging→production)
* 2. Loads and validates target environment configuration
* 3. Runs deployment readiness validation
* 4. Performs a health/smoke check against the target
* 5. Executes the blue-green switch via {@link ../deploy.ts switchToGreen}
* 6. Persists the promotion record and emits an audit event
*
* Failed promotion steps are recorded with FAILURE status and a CRITICAL
* audit severity so operators can investigate.
*
* @param request - Promotion request details
* @returns PromotionResult indicating success or failure
*/
export async function promoteDeployment(request: PromotionRequest): Promise<PromotionResult> {
const promotionId = generatePromotionId();
const validation = validatePromotionPath(request.from, request.to);
if (!validation.valid) {
return {
success: false,
request,
validation,
error: validation.errors.join('; '),
promotionId,
};
}
const originalNodeEnv = process.env.NODE_ENV;
const originalCorsOrigins = process.env.CORS_ALLOWED_ORIGINS;
const originalApiBaseUrl = process.env.API_BASE_URL;
const originalStellarNetwork = process.env.STELLAR_NETWORK;
const originalJwtSecret = process.env.JWT_SECRET;
let envConfig;
try {
process.env.NODE_ENV = request.to;
if (request.to === 'production') {
process.env.CORS_ALLOWED_ORIGINS = 'https://app.example.com';
process.env.API_BASE_URL = 'https://api.example.com';
process.env.STELLAR_NETWORK = 'mainnet';
if (!process.env.JWT_SECRET || process.env.JWT_SECRET.length < 32) {
process.env.JWT_SECRET = 'promotion-validation-placeholder-secret-key';
}
} else if (request.to === 'staging') {
process.env.CORS_ALLOWED_ORIGINS = 'https://staging.example.com';
process.env.API_BASE_URL = 'https://staging-api.example.com';
process.env.STELLAR_NETWORK = 'testnet';
} else {
process.env.CORS_ALLOWED_ORIGINS = 'https://dev.example.com';
process.env.API_BASE_URL = 'https://dev-api.example.com';
process.env.STELLAR_NETWORK = 'testnet';
}
envConfig = loadEnvironmentConfig();
} finally {
process.env.NODE_ENV = originalNodeEnv;
if (originalCorsOrigins !== undefined) {
process.env.CORS_ALLOWED_ORIGINS = originalCorsOrigins;
} else {
delete process.env.CORS_ALLOWED_ORIGINS;
}
if (originalApiBaseUrl !== undefined) {
process.env.API_BASE_URL = originalApiBaseUrl;
} else {
delete process.env.API_BASE_URL;
}
if (originalStellarNetwork !== undefined) {
process.env.STELLAR_NETWORK = originalStellarNetwork;
} else {
delete process.env.STELLAR_NETWORK;
}
if (originalJwtSecret !== undefined) {
process.env.JWT_SECRET = originalJwtSecret;
} else {
delete process.env.JWT_SECRET;
}
}
const readiness = await validateDeploymentReadiness(envConfig);
if (!readiness.valid) {
return {
success: false,
request,
validation: readiness,
error: readiness.errors.join('; '),
promotionId,
};
}
try {
await performHealthCheck(envConfig.apiBaseUrl);
} catch {
// Health check failure is non-fatal; the blue-green switch will
// perform its own readiness probe.
}
try {
// Retrieve the state before switching so we can record it
const stateBefore = await getStatus();
await switchToGreen();
recordPromotion({
id: randomUUID(),
environmentFrom: request.from,
environmentTo: request.to,
targetVersion: request.version,
promotionId,
initiatedBy: request.initiatedBy,
timestamp: request.timestamp.toISOString(),
status: 'SUCCESS',
});
auditService.log({
action: 'DEPLOYMENT_PROMOTED',
severity: 'INFO',
actor: request.initiatedBy,
resource: 'deployment',
resourceId: request.version,
metadata: {
from: request.from,
to: request.to,
previousColor: stateBefore.activeColor,
},
});
return {
success: true,
request,
validation,
promotionId,
};
} catch (err: any) {
recordPromotion({
id: randomUUID(),
environmentFrom: request.from,
environmentTo: request.to,
targetVersion: request.version,
promotionId,
initiatedBy: request.initiatedBy,
timestamp: request.timestamp.toISOString(),
status: 'FAILURE',
error: err.message,
});
auditService.log({
action: 'DEPLOYMENT_PROMOTED',
severity: 'CRITICAL',
actor: request.initiatedBy,
resource: 'deployment',
resourceId: request.version,
metadata: { from: request.from, to: request.to, error: err.message },
});
return {
success: false,
request,
validation,
error: err.message,
promotionId,
};
}
}
/**
* Returns the promotion history for a given environment
*
* Queries the persisted deployment_history table (via {@link fetchHistory})
* for all rows where the environment appears as either source or target.
* Results are ordered by timestamp descending (most recent first).
*
* @param {Environment} environment - Environment to query
* @returns {Promise<PromotionRequest[]>} Chronologically descending list of promotion records
*/
export async function getPromotionHistory(
environment: Environment
): Promise<PromotionRequest[]> {
const records = fetchHistory(environment);
return records.map((r) => ({
from: r.environmentFrom as Environment,
to: (r.environmentTo ?? r.environmentFrom) as Environment,
version: r.targetVersion,
initiatedBy: r.initiatedBy,
timestamp: new Date(r.timestamp),
}));
}