-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
262 lines (217 loc) · 9.87 KB
/
Copy pathmain.cpp
File metadata and controls
262 lines (217 loc) · 9.87 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
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <random> // Fix #5: Using modern <random> engine
#include <iomanip>
#include <algorithm>
#include <set>
#include "analytics_engine.h" // Integrated isolated analytics header
#include "url_database.h"
#include "semaphore.h"
// ============================================================================
// 1. DATA STRUCTURES & CONFIGURATIONS
// ============================================================================
struct URLData {
std::string original_url;
std::string short_code;
std::string alias;
int clicks = 0;
std::string qr_code;
std::chrono::system_clock::time_point expires_at;
};
// ============================================================================
// 3. SMART URL HOSTING PLATFORM ENGINE
// ============================================================================
class SmartURLPlatform {
private:
std::unordered_map<std::string, URLData> db;
std::unordered_map<std::string, std::string> alias_map;
std::mutex db_mutex;
Semaphore connection_pool;
// Memory and OS Simulation Profilers
std::vector<std::string> memory_access_history;
std::vector<ProcessMetrics> simulated_cpu_queue;
int pid_counter = 1000;
// Deadlock verification resources
std::mutex microservice_A_lock;
std::mutex microservice_B_lock;
// Fix #5: Replaced rand() with thread-safe high-quality Mersenne Twister engine
std::mt19937 rng;
std::string generateRandomCode() {
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::string code = "";
std::uniform_int_distribution<int> dist(0, sizeof(charset) - 2);
for (int i = 0; i < 6; ++i) {
code += charset[dist(rng)];
}
return code;
}
public:
SmartURLPlatform() : connection_pool(5), rng(std::random_device{}()) {}
void createShortURL(std::string original, std::string custom_alias = "", int expiry_seconds = 3600) {
connection_pool.wait();
std::lock_guard<std::mutex> lock(db_mutex);
// Fix #3: Duplicate Custom Alias check validation
if (!custom_alias.empty() && alias_map.count(custom_alias)) {
std::cout << " [ERROR] Alias \"" << custom_alias << "\" already exists! Request rejected.\n";
connection_pool.notify();
return;
}
std::uniform_int_distribution<int> arrival_dist(0, 2);
std::uniform_int_distribution<int> burst_dist(2, 6);
int arrival = simulated_cpu_queue.empty() ? 0 : simulated_cpu_queue.back().arrival_time + arrival_dist(rng);
int burst = burst_dist(rng);
simulated_cpu_queue.push_back({++pid_counter, "CREATE", burst, burst, arrival, 0, 0});
std::string code;
if (custom_alias.empty()) {
// Fix #2: Loop execution to eliminate short-code collisions
do {
code = generateRandomCode();
} while (db.find(code) != db.end());
} else {
code = custom_alias;
}
URLData url;
url.original_url = original;
url.short_code = code;
url.alias = custom_alias;
url.qr_code = "[QR Code Matrix for " + code + "]";
url.expires_at = std::chrono::system_clock::now() + std::chrono::seconds(expiry_seconds);
db[code] = url;
if (!custom_alias.empty()) {
alias_map[custom_alias] = code;
}
// Fix #7: Cap memory log traces to avoid long-term leakage footprints
if (memory_access_history.size() >= 1000) {
memory_access_history.erase(memory_access_history.begin());
}
memory_access_history.push_back(code);
connection_pool.notify();
}
std::string accessURL(std::string code) {
connection_pool.wait();
std::lock_guard<std::mutex> lock(db_mutex);
std::uniform_int_distribution<int> arrival_dist(0, 2);
std::uniform_int_distribution<int> burst_dist(1, 3);
int arrival = simulated_cpu_queue.empty() ? 0 : simulated_cpu_queue.back().arrival_time + arrival_dist(rng);
int burst = burst_dist(rng);
simulated_cpu_queue.push_back({++pid_counter, "REDIRECT", burst, burst, arrival, 0, 0});
if (memory_access_history.size() >= 1000) {
memory_access_history.erase(memory_access_history.begin());
}
memory_access_history.push_back(code);
if (alias_map.find(code) != alias_map.end()) {
code = alias_map[code];
}
if (db.find(code) != db.end()) {
// Fix #6: Evict expired records completely instead of leaving stale garbage entries
if (std::chrono::system_clock::now() > db[code].expires_at) {
if (!db[code].alias.empty()) {
alias_map.erase(db[code].alias);
}
db.erase(code);
connection_pool.notify();
return "ERROR: URL Expired and Evicted from System Storage!";
}
db[code].clicks++;
connection_pool.notify();
return db[code].original_url;
}
connection_pool.notify();
return "404 Not Found";
}
// Fix #6: Background maintenance module to target and remove remaining expired urls
void cleanExpiredURLs() {
std::lock_guard<std::mutex> lock(db_mutex);
auto now = std::chrono::system_clock::now();
for (auto it = db.begin(); it != db.end();) {
if (now > it->second.expires_at) {
if (!it->second.alias.empty()) {
alias_map.erase(it->second.alias);
}
it = db.erase(it);
} else {
++it;
}
}
}
// Fix #1: Elimination of random background thread lock hangs using std::scoped_lock
void simulateDeadlockCondition() {
std::cout << "\n=== [DEADLOCK MANAGEMENT SIMULATION ENGINE] ===\n";
auto worker1 = [this]() {
// std::scoped_lock locks all resources safely using a deadlock-avoidance algorithm
std::scoped_lock lock(microservice_A_lock, microservice_B_lock);
std::cout << "[Thread 1] Safely acquired Service A and B simultaneously.\n";
};
auto worker2 = [this]() {
std::scoped_lock lock(microservice_B_lock, microservice_A_lock);
std::cout << "[Thread 2] Safely acquired Service B and A simultaneously.\n";
};
std::cout << "Starting resource workers using safe variadic std::scoped_lock configurations...\n";
std::thread t1(worker1);
std::thread t2(worker2);
t1.join();
t2.join();
std::cout << "[DASHBOARD CHECK] Multithreading operations running clean without mutex-deadlock freezes!\n";
}
void displayDashboard() {
std::lock_guard<std::mutex> lock(db_mutex);
std::cout << "\n=======================================================\n";
std::cout << " 🚀 CPU & PLATFORM DASHBOARD \n";
std::cout << "=======================================================\n";
std::cout << " Active Mock Requests Logged: " << simulated_cpu_queue.size() << "\n";
std::cout << " Live Database Mapped Keys : " << db.size() << "\n";
std::cout << " Main CPU Utilization : " << (simulated_cpu_queue.empty() ? 0 : 87.4) << " %\n";
std::cout << " Thread State Queue Status : IDLE/RUNNING OK\n\n";
std::cout << "Link Analytics Log:\n";
for (const auto& [key, data] : db) {
std::cout << " - Short Code: [" << key << "] -> " << data.original_url
<< " | Total Hits: " << data.clicks << " | QR Graphic: " << data.qr_code << "\n";
}
std::cout << "=======================================================\n";
// Pass control blocks directly down into the isolated analytics pipeline
if(!simulated_cpu_queue.empty()) {
AnalyticsEngine::computeSchedulingAlgorithms(simulated_cpu_queue);
}
if(!memory_access_history.empty()) {
AnalyticsEngine::computePageReplacements(memory_access_history, 3);
}
}
};
// ============================================================================
// 4. MAIN SYSTEM SYSTEM ENTRYPOINT
// ============================================================================
int main() {
SmartURLPlatform platform;
std::cout << "Initializing SmartURL Secure System Infrastructure Threads...\n";
// Simulate multi-threaded user environment traffic via concurrent lambdas
std::thread user1(&SmartURLPlatform::createShortURL, &platform, "https://google.com", "goog", 3600);
std::thread user2(&SmartURLPlatform::createShortURL, &platform, "https://github.com", "", 3600);
std::thread user3(&SmartURLPlatform::createShortURL, &platform, "https://stackoverflow.com", "so", 3600);
user1.join();
user2.join();
user3.join();
// Trigger explicit testing for custom alias collision prevention
std::cout << "\n--- Testing Alias Collision Protection ---\n";
platform.createShortURL("https://microsoft.com", "goog", 3600);
// Trigger parallel redirection load
std::thread client1([&]() { platform.accessURL("goog"); });
std::thread client2([&]() { platform.accessURL("so"); });
std::thread client3([&]() { platform.accessURL("goog"); });
client1.join();
client2.join();
client3.join();
// Run proactive maintenance cleaner sweep loop
platform.cleanExpiredURLs();
// Fire Analytics, UI Metrics Dashboard, and Deadlock Modules
platform.displayDashboard();
platform.simulateDeadlockCondition();
std::cout << "\nTerminating Engine System Execution Thread Pool Safely. Done!\n";
return 0;
}