-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin-lifecycle-advanced.zod.ts
More file actions
482 lines (419 loc) · 13 KB
/
plugin-lifecycle-advanced.zod.ts
File metadata and controls
482 lines (419 loc) · 13 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
/**
* # Advanced Plugin Lifecycle Protocol
*
* Defines advanced lifecycle management capabilities including:
* - Hot reload and live updates
* - Graceful degradation and fallback mechanisms
* - Health monitoring and auto-recovery
* - State preservation during updates
*
* This protocol extends the basic plugin lifecycle with enterprise-grade
* features for production environments.
*/
/**
* Plugin Health Status
* Represents the current operational state of a plugin
*/
export const PluginHealthStatusSchema = z.enum([
'healthy', // Plugin is operating normally
'degraded', // Plugin is operational but with reduced functionality
'unhealthy', // Plugin has critical issues but still running
'failed', // Plugin has failed and is not operational
'recovering', // Plugin is in recovery process
'unknown', // Health status cannot be determined
]).describe('Current health status of the plugin');
/**
* Plugin Health Check Configuration
* Defines how to check plugin health
*/
export const PluginHealthCheckSchema = z.object({
/**
* Health check interval in milliseconds
*/
interval: z.number().int().min(1000).default(30000)
.describe('How often to perform health checks (default: 30s)'),
/**
* Timeout for health check in milliseconds
*/
timeout: z.number().int().min(100).default(5000)
.describe('Maximum time to wait for health check response'),
/**
* Number of consecutive failures before marking as unhealthy
*/
failureThreshold: z.number().int().min(1).default(3)
.describe('Consecutive failures needed to mark unhealthy'),
/**
* Number of consecutive successes to recover from unhealthy state
*/
successThreshold: z.number().int().min(1).default(1)
.describe('Consecutive successes needed to mark healthy'),
/**
* Custom health check function name or endpoint
*/
checkMethod: z.string().optional()
.describe('Method name to call for health check'),
/**
* Enable automatic restart on failure
*/
autoRestart: z.boolean().default(false)
.describe('Automatically restart plugin on health check failure'),
/**
* Maximum number of restart attempts
*/
maxRestartAttempts: z.number().int().min(0).default(3)
.describe('Maximum restart attempts before giving up'),
/**
* Backoff strategy for restarts
*/
restartBackoff: z.enum(['fixed', 'linear', 'exponential']).default('exponential')
.describe('Backoff strategy for restart delays'),
});
/**
* Plugin Health Report
* Detailed health information from a plugin
*/
export const PluginHealthReportSchema = z.object({
/**
* Overall health status
*/
status: PluginHealthStatusSchema,
/**
* Timestamp of the health check
*/
timestamp: z.string().datetime(),
/**
* Human-readable message about health status
*/
message: z.string().optional(),
/**
* Detailed metrics
*/
metrics: z.object({
uptime: z.number().describe('Plugin uptime in milliseconds'),
memoryUsage: z.number().optional().describe('Memory usage in bytes'),
cpuUsage: z.number().optional().describe('CPU usage percentage'),
activeConnections: z.number().optional().describe('Number of active connections'),
errorRate: z.number().optional().describe('Error rate (errors per minute)'),
responseTime: z.number().optional().describe('Average response time in ms'),
}).partial().optional(),
/**
* List of checks performed
*/
checks: z.array(z.object({
name: z.string().describe('Check name'),
status: z.enum(['passed', 'failed', 'warning']),
message: z.string().optional(),
data: z.record(z.string(), z.unknown()).optional(),
})).optional(),
/**
* Dependencies health
*/
dependencies: z.array(z.object({
pluginId: z.string(),
status: PluginHealthStatusSchema,
message: z.string().optional(),
})).optional(),
});
/**
* Distributed State Configuration
* Configuration for distributed state management in cluster environments
*/
export const DistributedStateConfigSchema = z.object({
/**
* Distributed cache provider
*/
provider: z.enum(['redis', 'etcd', 'custom'])
.describe('Distributed state backend provider'),
/**
* Connection URL or endpoints
*/
endpoints: z.array(z.string()).optional()
.describe('Backend connection endpoints'),
/**
* Key prefix for namespacing
*/
keyPrefix: z.string().optional()
.describe('Prefix for all keys (e.g., "plugin:my-plugin:")'),
/**
* Time to live in seconds
*/
ttl: z.number().int().min(0).optional()
.describe('State expiration time in seconds'),
/**
* Authentication configuration
*/
auth: z.object({
username: z.string().optional(),
password: z.string().optional(),
token: z.string().optional(),
certificate: z.string().optional(),
}).optional(),
/**
* Replication settings
*/
replication: z.object({
enabled: z.boolean().default(true),
minReplicas: z.number().int().min(1).default(1),
}).optional(),
/**
* Custom provider configuration
*/
customConfig: z.record(z.string(), z.unknown()).optional()
.describe('Provider-specific configuration'),
});
/**
* Hot Reload Configuration
* Controls how plugins handle live updates
*/
export const HotReloadConfigSchema = z.object({
/**
* Enable hot reload capability
*/
enabled: z.boolean().default(false),
/**
* Watch file patterns for auto-reload
*/
watchPatterns: z.array(z.string()).optional()
.describe('Glob patterns to watch for changes'),
/**
* Debounce delay before reloading (milliseconds)
*/
debounceDelay: z.number().int().min(0).default(1000)
.describe('Wait time after change detection before reload'),
/**
* Preserve plugin state during reload
*/
preserveState: z.boolean().default(true)
.describe('Keep plugin state across reloads'),
/**
* State serialization strategy
*/
stateStrategy: z.enum(['memory', 'disk', 'distributed', 'none']).default('memory')
.describe('How to preserve state during reload'),
/**
* Distributed state configuration (required when stateStrategy is "distributed")
*/
distributedConfig: DistributedStateConfigSchema.optional()
.describe('Configuration for distributed state management'),
/**
* Graceful shutdown timeout
*/
shutdownTimeout: z.number().int().min(0).default(30000)
.describe('Maximum time to wait for graceful shutdown'),
/**
* Pre-reload hooks
*/
beforeReload: z.array(z.string()).optional()
.describe('Hook names to call before reload'),
/**
* Post-reload hooks
*/
afterReload: z.array(z.string()).optional()
.describe('Hook names to call after reload'),
});
/**
* Graceful Degradation Configuration
* Defines how plugin degrades when dependencies fail
*/
export const GracefulDegradationSchema = z.object({
/**
* Enable graceful degradation
*/
enabled: z.boolean().default(true),
/**
* Fallback mode when dependencies fail
*/
fallbackMode: z.enum([
'minimal', // Provide minimal functionality
'cached', // Use cached data
'readonly', // Allow read-only operations
'offline', // Offline mode with local data
'disabled', // Disable plugin functionality
]).default('minimal'),
/**
* Critical dependencies that must be available
*/
criticalDependencies: z.array(z.string()).optional()
.describe('Plugin IDs that are required for operation'),
/**
* Optional dependencies that can fail
*/
optionalDependencies: z.array(z.string()).optional()
.describe('Plugin IDs that are nice to have but not required'),
/**
* Feature flags for degraded mode
*/
degradedFeatures: z.array(z.object({
feature: z.string().describe('Feature name'),
enabled: z.boolean().describe('Whether feature is available in degraded mode'),
reason: z.string().optional(),
})).optional(),
/**
* Automatic recovery attempts
*/
autoRecovery: z.object({
enabled: z.boolean().default(true),
retryInterval: z.number().int().min(1000).default(60000)
.describe('Interval between recovery attempts (ms)'),
maxAttempts: z.number().int().min(0).default(5)
.describe('Maximum recovery attempts before giving up'),
}).optional(),
});
/**
* Plugin Update Strategy
* Defines how plugin handles version updates
*/
export const PluginUpdateStrategySchema = z.object({
/**
* Update mode
*/
mode: z.enum([
'manual', // Manual updates only
'automatic', // Automatic updates
'scheduled', // Scheduled update windows
'rolling', // Rolling updates with zero downtime
]).default('manual'),
/**
* Version constraints for automatic updates
*/
autoUpdateConstraints: z.object({
major: z.boolean().default(false).describe('Allow major version updates'),
minor: z.boolean().default(true).describe('Allow minor version updates'),
patch: z.boolean().default(true).describe('Allow patch version updates'),
}).optional(),
/**
* Update schedule (for scheduled mode)
*/
schedule: z.object({
/**
* Cron expression for update window
*/
cron: z.string().optional(),
/**
* Timezone for schedule
*/
timezone: z.string().default('UTC'),
/**
* Maintenance window duration in minutes
*/
maintenanceWindow: z.number().int().min(1).default(60),
}).optional(),
/**
* Rollback configuration
*/
rollback: z.object({
enabled: z.boolean().default(true),
/**
* Automatic rollback on failure
*/
automatic: z.boolean().default(true),
/**
* Keep N previous versions for rollback
*/
keepVersions: z.number().int().min(1).default(3),
/**
* Rollback timeout in milliseconds
*/
timeout: z.number().int().min(1000).default(30000),
}).optional(),
/**
* Pre-update validation
*/
validation: z.object({
/**
* Run compatibility checks before update
*/
checkCompatibility: z.boolean().default(true),
/**
* Run tests before applying update
*/
runTests: z.boolean().default(false),
/**
* Test suite to run
*/
testSuite: z.string().optional(),
}).optional(),
});
/**
* Plugin State Snapshot
* Captures plugin state for preservation during updates/reloads
*/
export const PluginStateSnapshotSchema = z.object({
/**
* Plugin identifier
*/
pluginId: z.string(),
/**
* Version at time of snapshot
*/
version: z.string(),
/**
* Snapshot timestamp
*/
timestamp: z.string().datetime(),
/**
* Serialized state data
*/
state: z.record(z.string(), z.unknown()),
/**
* State metadata
*/
metadata: z.object({
checksum: z.string().optional().describe('State checksum for verification'),
compressed: z.boolean().default(false),
encryption: z.string().optional().describe('Encryption algorithm if encrypted'),
}).optional(),
});
/**
* Advanced Plugin Lifecycle Configuration
* Complete configuration for advanced lifecycle management
*/
export const AdvancedPluginLifecycleConfigSchema = z.object({
/**
* Health monitoring configuration
*/
health: PluginHealthCheckSchema.optional(),
/**
* Hot reload configuration
*/
hotReload: HotReloadConfigSchema.optional(),
/**
* Graceful degradation configuration
*/
degradation: GracefulDegradationSchema.optional(),
/**
* Update strategy
*/
updates: PluginUpdateStrategySchema.optional(),
/**
* Resource limits
*/
resources: z.object({
maxMemory: z.number().int().optional().describe('Maximum memory in bytes'),
maxCpu: z.number().min(0).max(100).optional().describe('Maximum CPU percentage'),
maxConnections: z.number().int().optional().describe('Maximum concurrent connections'),
timeout: z.number().int().optional().describe('Operation timeout in milliseconds'),
}).optional(),
/**
* Monitoring and observability
*/
observability: z.object({
enableMetrics: z.boolean().default(true),
enableTracing: z.boolean().default(true),
enableProfiling: z.boolean().default(false),
metricsInterval: z.number().int().min(1000).default(60000)
.describe('Metrics collection interval in ms'),
}).optional(),
});
// Export types
export type PluginHealthStatus = z.infer<typeof PluginHealthStatusSchema>;
export type PluginHealthCheck = z.infer<typeof PluginHealthCheckSchema>;
export type PluginHealthReport = z.infer<typeof PluginHealthReportSchema>;
export type DistributedStateConfig = z.infer<typeof DistributedStateConfigSchema>;
export type HotReloadConfig = z.infer<typeof HotReloadConfigSchema>;
export type GracefulDegradation = z.infer<typeof GracefulDegradationSchema>;
export type PluginUpdateStrategy = z.infer<typeof PluginUpdateStrategySchema>;
export type PluginStateSnapshot = z.infer<typeof PluginStateSnapshotSchema>;
export type AdvancedPluginLifecycleConfig = z.infer<typeof AdvancedPluginLifecycleConfigSchema>;