ScriptsLab
WikiDownloadsSourcesSupport
ScriptsLab
DocumentationDownloadsGitHubDiscord

© 2026 ScriptsLab

Back to root
M

ARCHITECTURE.md

Markdown · 389 lines · 9.7 KB

ARCHITECTURE.md
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
# Framework Architecture

## Overview

FrameworkPlugin is a production-grade, modular plugin framework for Minecraft Paper servers. It follows Clean Architecture principles with strict separation of concerns.

## Architecture Layers

```
┌─────────────────────────────────────────┐
│           Presentation Layer            │
│  (Commands, Events, GUI)                │
├─────────────────────────────────────────┤
│           Application Layer             │
│  (Use Cases, Business Logic)            │
├─────────────────────────────────────────┤
│           Domain Layer (API)            │
│  (Interfaces, Entities, Value Objects)  │
├─────────────────────────────────────────┤
│        Infrastructure Layer (Core)      │
│  (Implementations, External Services)   │
└─────────────────────────────────────────┘
```

## Core Components

### 1. Dependency Injection Container

**Location**: `core/di/Container.java`

**Purpose**: Lightweight DI container for service management

**Features**:
- Singleton registration
- Factory registration
- Thread-safe (double-checked locking)
- Type-safe resolution

**Usage**:
```java
Container container = Container.getInstance();
container.registerSingleton(EventBus.class, new EventBusImpl());
EventBus eventBus = container.resolve(EventBus.class).orElseThrow();
```

### 2. Module System

**Location**: `api/module/`, `core/module/`

**Purpose**: Dynamic module loading with dependency resolution

**Features**:
- Topological sorting for load order
- Dependency validation
- Hot reload support
- Lifecycle management (load → enable → disable → unload)

**Module Lifecycle**:
```
┌──────┐    ┌────────┐    ┌─────────┐    ┌──────────┐
│ Load │ -> │ Enable │ -> │ Running │ -> │ Disable  │
└──────┘    └────────┘    └─────────┘    └──────────┘
                              ↓                ↓
                          ┌────────┐      ┌────────┐
                          │ Reload │      │ Unload │
                          └────────┘      └────────┘
```

### 3. Event Bus

**Location**: `api/event/`, `core/event/`

**Purpose**: Custom event system for cross-module communication

**Features**:
- Priority-based event handling
- Cancellable events
- Async event posting
- Type-safe subscriptions

**Event Flow**:
```
Publisher -> EventBus -> [Priority Queue] -> Subscribers
                              ↓
                         [LOWEST → LOW → NORMAL → HIGH → HIGHEST → MONITOR]
```

### 4. Script Engine

**Location**: `api/script/`, `core/script/`

**Purpose**: Sandboxed JavaScript execution using GraalVM

**Features**:
- ECMAScript 2022 support
- Sandboxing (no file I/O, restricted class access)
- Hot reload
- Error isolation
- Execution tracking

**Security Model**:
```
JavaScript Code
      ↓
  Sandbox Layer (GraalVM Context)
      ↓
  API Layer (ScriptAPIImpl)
      ↓
  Plugin Services
```

### 5. Item System

**Location**: `api/item/`, `core/item/`

**Purpose**: Custom items with abilities and NBT data

**Features**:
- Immutable item definitions
- Ability system with cooldowns
- NBT persistence
- Rarity system
- Builder pattern for creation

**Item Structure**:
```
CustomItem
├── ID (unique identifier)
├── Material (base Bukkit material)
├── Display Name
├── Lore
├── Custom Model Data
├── NBT Data (key-value pairs)
├── Abilities (list of ItemAbility)
├── Rarity (COMMON → MYTHIC)
└── Unbreakable flag
```

### 6. Task Scheduler

**Location**: `api/scheduler/`, `core/scheduler/`

**Purpose**: Wrapper around BukkitScheduler with better API

**Features**:
- CompletableFuture support
- TimeUnit-based delays
- Task tracking
- Owner-based cancellation

## Design Patterns

### 1. Dependency Injection
- **Where**: Throughout the framework
- **Why**: Loose coupling, testability, flexibility

### 2. Repository Pattern
- **Where**: Storage layer
- **Why**: Abstract data access, swappable backends

### 3. Observer Pattern
- **Where**: Event bus
- **Why**: Decoupled communication

### 4. Strategy Pattern
- **Where**: Storage providers
- **Why**: Pluggable storage backends

### 5. Builder Pattern
- **Where**: Item creation, GUI building
- **Why**: Fluent API, immutability

### 6. Factory Pattern
- **Where**: Module creation
- **Why**: Encapsulate object creation

### 7. Singleton Pattern
- **Where**: DI container, managers
- **Why**: Single instance, global access (thread-safe)

## Thread Safety

### Concurrency Strategy

1. **Immutable Objects**: All API entities are immutable (records)
2. **Concurrent Collections**: ConcurrentHashMap for all registries
3. **Atomic Operations**: AtomicBoolean, AtomicInteger for state
4. **CompletableFuture**: All async operations return futures
5. **No Shared Mutable State**: Each module has isolated state

### Thread Model

```
Main Thread (Bukkit)
├── Event Handling
├── Command Execution
└── Synchronous Tasks

Async Thread Pool
├── Module Loading
├── Script Execution
├── Storage Operations
└── Heavy Computations
```

## Performance Optimizations

### 1. Lazy Loading
- Modules load on-demand
- Configs load when first accessed
- Scripts compile once, execute many times

### 2. Caching
- Module descriptors cached
- Item definitions cached
- Script contexts reused

### 3. Batch Operations
- Storage batch saves
- Event batch processing
- Cooldown cleanup batching

### 4. Async I/O
- All file operations async
- Database operations async
- Network operations async

### 5. Object Pooling
- Reuse expensive objects
- Minimize allocations
- Reduce GC pressure

## Error Handling

### Strategy

1. **Fail Fast**: Validate early, throw exceptions
2. **Graceful Degradation**: Continue on non-critical errors
3. **Error Isolation**: Module errors don't crash plugin
4. **Detailed Logging**: All errors logged with context
5. **Recovery**: Auto-recovery where possible

### Error Flow

```
Error Occurs
    ↓
Log Error (with context)
    ↓
Notify Affected Components
    ↓
Attempt Recovery
    ↓
If Recovery Fails → Disable Component
    ↓
Continue Plugin Operation
```

## Extension Points

### 1. Custom Modules
Implement `Module` interface or extend `BaseModule`

### 2. Custom Storage Providers
Implement `StorageProvider` interface

### 3. Custom Item Abilities
Implement `ItemAbility` interface

### 4. Custom Events
Implement `PluginEvent` interface

### 5. Script API Extensions
Add methods to `ScriptAPIImpl`

## Testing Strategy

### Unit Tests
- Test individual components in isolation
- Mock dependencies
- Fast execution

### Integration Tests
- Test component interactions
- Use test containers
- Realistic scenarios

### Performance Tests
- Load testing
- Stress testing
- Memory profiling

## Deployment

### Development
```
mvn clean package
→ Copy to test server
→ Reload plugin
→ Test changes
```

### Production
```
mvn clean package -P production
→ Run tests
→ Security scan
→ Deploy to server
→ Monitor logs
```

## Monitoring

### Metrics to Track
- Module load times
- Script execution times
- Event processing times
- Memory usage
- Active tasks count
- Error rates

### Logging Levels
- **SEVERE**: Critical errors
- **WARNING**: Non-critical issues
- **INFO**: Important events
- **FINE**: Debug information
- **FINER**: Detailed debug
- **FINEST**: Trace level

## Future Enhancements

1. **Web Dashboard**: Real-time monitoring and control
2. **Database Integration**: MySQL, PostgreSQL support
3. **Metrics System**: Prometheus integration
4. **Hot Code Reload**: Reload Java code without restart
5. **Distributed Modules**: Load modules from remote sources
6. **API Gateway**: REST API for external integrations
7. **Plugin Marketplace**: Download modules from repository

## Best Practices

### For Module Developers

1. **Use DI Container**: Don't create services manually
2. **Async Operations**: Use CompletableFuture for I/O
3. **Error Handling**: Catch and log all exceptions
4. **Resource Cleanup**: Unregister everything in onDisable
5. **Thread Safety**: Use concurrent collections
6. **Documentation**: Document all public APIs

### For Script Developers

1. **Keep Scripts Small**: One responsibility per script
2. **Error Handling**: Use try-catch in scripts
3. **Avoid Blocking**: Don't block the main thread
4. **Use API**: Don't access Bukkit directly
5. **Test Thoroughly**: Test scripts before deployment

## Troubleshooting

### Common Issues

1. **Module Won't Load**
   - Check dependencies in module.yml
   - Verify module.yml syntax
   - Check logs for errors

2. **Script Errors**
   - Check script syntax
   - Verify API usage
   - Enable debug logging

3. **Performance Issues**
   - Profile with JProfiler
   - Check for memory leaks
   - Review async operations

4. **Thread Deadlocks**
   - Use thread dumps
   - Review synchronization
   - Check for circular waits

## Resources

- [Paper API Documentation](https://docs.papermc.io/)
- [GraalVM Documentation](https://www.graalvm.org/latest/docs/)
- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)
- [SOLID Principles](https://en.wikipedia.org/wiki/SOLID)