-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnoneDB.php
More file actions
9018 lines (7765 loc) · 300 KB
/
noneDB.php
File metadata and controls
9018 lines (7765 loc) · 300 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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* https://github.com/orhanayd/noneDB
*
* first this project start date 15.11.2018
* noneDB - 20.08.2019 -- Orhan AYDOĞDU
* OPEN SOURCE <3
* please read firstly noneDB documents if your data is important ::)))
* but every data is important for us <3
* created with love <3 || ORHAN AYDOGDU || www.orhanaydogdu.com.tr || info@orhanaydogdu.com.tr
* Respect for Labour - Emeğe Saygı
*/
ini_set('memory_limit', '-1');
class noneDB {
// Configuration file path (relative to dbDir or absolute)
private static $configFile = '.nonedb';
private static $configLoaded = false;
private static $configData = null;
private $dbDir = null; // Set via .nonedb config file or constructor
private $secretKey = null; // Set via .nonedb config file or constructor
private $autoCreateDB = true;
// Sharding configuration
private $shardingEnabled=true; // Enable/disable auto-sharding
private $shardSize=10000; // Max records per shard (10K) - optimal for filter operations
private $autoMigrate=true; // Auto-migrate legacy DBs to sharded format
// File locking configuration
private $lockTimeout=5; // Max seconds to wait for lock
private $lockRetryDelay=10000; // Microseconds between lock attempts (10ms)
// Write buffer configuration
private $bufferEnabled=true; // Enable/disable write buffering
private $bufferSizeLimit=1048576; // 1MB buffer size limit per buffer
private $bufferCountLimit=10000; // Max records per buffer (safety limit)
private $bufferFlushOnRead=true; // Flush buffer before read operations
private $bufferFlushInterval=30; // Seconds between auto-flush (0 = disabled)
private $bufferAutoFlushOnShutdown=true; // Register shutdown handler for flush
// Buffer state tracking (runtime)
private $bufferLastFlush=[]; // Track last flush time per DB/shard
private $shutdownHandlerRegistered=false; // Track if shutdown handler is registered
// Performance cache (runtime) - v2.3.0
private $hashCache=[]; // Cache dbname -> hash (PBKDF2 is expensive)
private $metaCache=[]; // Cache dbname -> meta data
private $metaCacheTime=[]; // Cache timestamps for TTL
private $metaCacheTTL=1; // Meta cache TTL in seconds (short for consistency)
// Index configuration - v2.3.0
private $indexEnabled=true; // Enable/disable primary key indexing
private $indexCache=[]; // Runtime cache for index data
private $shardedCache=[]; // Cache isSharded results
// JSONL Storage Engine - v3.0.0 (JSONL-only, v2 format removed)
private $jsonlFormatCache=[]; // Cache format detection per DB
private $jsonlGarbageThreshold=0.3; // Trigger compaction when garbage > 30%
// Static caches for cross-instance sharing - v3.0.0
private static $staticIndexCache=[]; // Shared index cache across instances
private static $staticShardedCache=[]; // Shared isSharded results
private static $staticMetaCache=[]; // Shared meta data cache
private static $staticMetaCacheTime=[]; // Shared meta cache timestamps
private static $staticHashCache=[]; // Shared hash cache (PBKDF2 is expensive)
private static $staticFormatCache=[]; // Shared format detection cache
private static $staticFileExistsCache=[]; // Shared file_exists cache - v3.0.0
private static $staticSanitizeCache=[]; // Shared dbname sanitization cache - v3.0.0
private static $staticFieldIndexCache=[]; // Shared field index cache - v3.0.0
private static $staticSpatialIndexCache=[]; // Shared spatial R-tree index cache - v3.1.0
private static $staticGlobalSpatialIndexCache=[]; // Shared global spatial index cache - v3.1.0
private static $staticCacheEnabled=true; // Enable/disable static caching
// Field indexing configuration - v3.0.0
private $fieldIndexEnabled = true; // Enable field-based indexing
private $fieldIndexCache = []; // Instance-level field index cache
// Spatial indexing configuration - v3.1.0
private $spatialIndexEnabled = true; // Enable spatial R-tree indexing
private $spatialIndexCache = []; // Instance-level spatial index cache
private $globalSpatialIndexCache = []; // Instance-level global spatial index cache
private $rtreeNodeSize = 32; // Max entries per R-tree node (increased from 16 for fewer splits)
private $dirtySpatialIndexes = []; // Dirty flags for batch spatial writes
private $distanceCache = []; // Haversine distance memoization cache
private $centroidCache = []; // Geometry centroid cache
// Persistent hash cache - v3.0.0 performance optimization
private $hashCacheFile = null; // Path to persistent hash cache file
private $hashCacheDirty = false; // Track if hash cache needs saving
private $hashCacheLoaded = false; // Track if persistent cache was loaded
/**
* Constructor - load config and initialize static caches
* @param array|null $config Optional config array to override file config
* @throws \RuntimeException If config file is missing in production mode
*/
public function __construct($config = null){
// Load configuration
$this->loadConfig($config);
// Link instance caches to static caches for cross-instance sharing
if(self::$staticCacheEnabled){
$this->indexCache = &self::$staticIndexCache;
$this->shardedCache = &self::$staticShardedCache;
$this->metaCache = &self::$staticMetaCache;
$this->metaCacheTime = &self::$staticMetaCacheTime;
$this->hashCache = &self::$staticHashCache;
$this->jsonlFormatCache = &self::$staticFormatCache;
$this->fieldIndexCache = &self::$staticFieldIndexCache;
$this->spatialIndexCache = &self::$staticSpatialIndexCache;
$this->globalSpatialIndexCache = &self::$staticGlobalSpatialIndexCache;
}
// Register shutdown function to flush dirty spatial indexes
register_shutdown_function([$this, 'flushSpatialIndexes']);
}
/**
* Load configuration from file or array
* Config file locations checked (in order):
* 1. .nonedb in project root (dirname of including script)
* 2. .nonedb in noneDB.php directory
* 3. .nonedb in dbDir
*
* @param array|null $config Optional config array
* @throws \RuntimeException If config file missing and not in dev mode
*/
private function loadConfig($config = null){
// If config array provided, use it directly
if(is_array($config)){
$this->applyConfig($config);
return;
}
// If already loaded from file, just apply
if(self::$configLoaded && self::$configData !== null){
$this->applyConfig(self::$configData);
return;
}
// Try to find config file
$configPaths = [
dirname($_SERVER['SCRIPT_FILENAME'] ?? __DIR__) . '/' . self::$configFile,
__DIR__ . '/' . self::$configFile,
$this->dbDir . self::$configFile
];
$configPath = null;
foreach($configPaths as $path){
if(file_exists($path)){
$configPath = $path;
break;
}
}
if($configPath !== null){
// Config file found - load it
$content = @file_get_contents($configPath);
if($content === false){
throw new \RuntimeException("noneDB: Cannot read config file: {$configPath}");
}
$data = @json_decode($content, true);
if($data === null && json_last_error() !== JSON_ERROR_NONE){
throw new \RuntimeException("noneDB: Invalid JSON in config file: {$configPath}");
}
self::$configData = $data;
self::$configLoaded = true;
$this->applyConfig($data);
return;
}
// No config file found
// Check for development mode
$devMode = getenv('NONEDB_DEV_MODE') === 'true'
|| getenv('NONEDB_DEV_MODE') === '1'
|| (defined('NONEDB_DEV_MODE') && NONEDB_DEV_MODE === true);
if($devMode){
// Dev mode - use defaults
self::$configLoaded = true;
self::$configData = [];
// Set default values for dev mode
$this->dbDir = __DIR__ . '/db/';
$this->secretKey = 'nonedb_dev_mode_key_' . md5(__DIR__);
return;
}
// Production mode without config file - throw error
throw new \RuntimeException(
"noneDB: Configuration file not found!\n" .
"Create a '.nonedb' config file in your project root.\n" .
"See '.nonedb.example' for reference.\n" .
"For development, set NONEDB_DEV_MODE=true environment variable or define('NONEDB_DEV_MODE', true);"
);
}
/**
* Apply configuration values to instance properties
* @param array $config Configuration array
*/
private function applyConfig(array $config){
// Core settings
if(isset($config['secretKey'])){
$this->secretKey = $config['secretKey'];
}
if(isset($config['dbDir'])){
// Handle relative paths
$dbDir = $config['dbDir'];
if(substr($dbDir, 0, 2) === './'){
$dbDir = dirname($_SERVER['SCRIPT_FILENAME'] ?? __DIR__) . '/' . substr($dbDir, 2);
}
if(substr($dbDir, -1) !== '/'){
$dbDir .= '/';
}
$this->dbDir = $dbDir;
}
if(isset($config['autoCreateDB'])){
$this->autoCreateDB = (bool)$config['autoCreateDB'];
}
// Sharding settings
if(isset($config['shardingEnabled'])){
$this->shardingEnabled = (bool)$config['shardingEnabled'];
}
if(isset($config['shardSize'])){
$this->shardSize = (int)$config['shardSize'];
}
if(isset($config['autoMigrate'])){
$this->autoMigrate = (bool)$config['autoMigrate'];
}
// Compaction settings
if(isset($config['autoCompactThreshold'])){
$this->jsonlGarbageThreshold = (float)$config['autoCompactThreshold'];
}
// Lock settings
if(isset($config['lockTimeout'])){
$this->lockTimeout = (int)$config['lockTimeout'];
}
if(isset($config['lockRetryDelay'])){
$this->lockRetryDelay = (int)$config['lockRetryDelay'];
}
}
/**
* Check if config file exists
* @return bool
*/
public static function configExists(): bool {
$configPaths = [
dirname($_SERVER['SCRIPT_FILENAME'] ?? __DIR__) . '/' . self::$configFile,
__DIR__ . '/' . self::$configFile
];
foreach($configPaths as $path){
if(file_exists($path)){
return true;
}
}
return false;
}
/**
* Get the config file template path
* @return string|null
*/
public static function getConfigTemplate(): ?string {
$templatePath = __DIR__ . '/.nonedb.example';
return file_exists($templatePath) ? $templatePath : null;
}
/**
* Clear config cache (useful for testing)
* @return void
*/
public static function clearConfigCache(): void {
self::$configLoaded = false;
self::$configData = null;
}
/**
* Set development mode programmatically
* Useful for testing or when env vars are not available
* @param bool $enabled
* @return void
*/
public static function setDevMode(bool $enabled): void {
if($enabled && !defined('NONEDB_DEV_MODE')){
define('NONEDB_DEV_MODE', true);
}
}
/**
* Destructor - save persistent hash cache
* v3.0.0 performance optimization
*/
public function __destruct(){
$this->savePersistentHashCache();
}
/**
* Load hash cache from persistent storage
* v3.0.0 performance optimization: Eliminates PBKDF2 computation on subsequent requests
* @return void
*/
private function loadPersistentHashCache(){
if($this->hashCacheLoaded){
return;
}
$this->hashCacheLoaded = true;
if($this->hashCacheFile === null){
$this->hashCacheFile = $this->dbDir . '.nonedb_hash_cache';
}
if(file_exists($this->hashCacheFile)){
$data = @file_get_contents($this->hashCacheFile);
if($data !== false && $data !== ''){
$loaded = @json_decode($data, true);
if(is_array($loaded) && !empty($loaded)){
// Merge into hash cache
foreach($loaded as $dbname => $hash){
if(!isset($this->hashCache[$dbname])){
$this->hashCache[$dbname] = $hash;
}
}
// Also update static cache if enabled
if(self::$staticCacheEnabled){
self::$staticHashCache = $this->hashCache;
}
}
}
}
}
/**
* Save hash cache to persistent storage
* v3.0.0 performance optimization: Persists PBKDF2 results across PHP requests
* @return void
*/
private function savePersistentHashCache(){
if(!$this->hashCacheDirty || empty($this->hashCache)){
return;
}
if($this->hashCacheFile === null){
$this->hashCacheFile = $this->dbDir . '.nonedb_hash_cache';
}
@file_put_contents($this->hashCacheFile, json_encode($this->hashCache));
$this->hashCacheDirty = false;
}
/**
* Clear all static caches (useful for testing or memory management)
* @return void
*/
public static function clearStaticCache(){
self::$staticIndexCache = [];
self::$staticShardedCache = [];
self::$staticMetaCache = [];
self::$staticMetaCacheTime = [];
self::$staticHashCache = [];
self::$staticFormatCache = [];
self::$staticFileExistsCache = [];
self::$staticSanitizeCache = [];
self::$staticFieldIndexCache = [];
self::$staticSpatialIndexCache = [];
self::$staticGlobalSpatialIndexCache = [];
}
/**
* Disable static caching (each instance uses its own cache)
* @return void
*/
public static function disableStaticCache(){
self::$staticCacheEnabled = false;
}
/**
* Enable static caching (default)
* @return void
*/
public static function enableStaticCache(){
self::$staticCacheEnabled = true;
}
/**
* Cached file_exists check - v3.0.0
* Reduces disk I/O by caching file existence checks
*
* @param string $path File path to check
* @return bool True if file exists
*/
private function cachedFileExists($path){
if(!self::$staticCacheEnabled){
return file_exists($path);
}
if(isset(self::$staticFileExistsCache[$path])){
return self::$staticFileExistsCache[$path];
}
$exists = file_exists($path);
self::$staticFileExistsCache[$path] = $exists;
return $exists;
}
/**
* Mark file as existing in cache (call after creating file)
* @param string $path File path
*/
private function markFileExists($path){
if(self::$staticCacheEnabled){
self::$staticFileExistsCache[$path] = true;
}
}
/**
* Mark file as not existing in cache (call after deleting file)
* @param string $path File path
*/
private function markFileNotExists($path){
if(self::$staticCacheEnabled){
self::$staticFileExistsCache[$path] = false;
}
}
/**
* Invalidate file exists cache for a specific path
* @param string $path File path
*/
private function invalidateFileExistsCache($path){
unset(self::$staticFileExistsCache[$path]);
}
/**
* Sanitize database name - removes invalid characters
* Uses static cache to avoid redundant regex operations - v3.0.0
*
* @param string $dbname Database name to sanitize
* @return string Sanitized database name
*/
private function sanitizeDbName($dbname){
if(!self::$staticCacheEnabled){
return preg_replace("/[^A-Za-z0-9' -]/", '', $dbname);
}
if(isset(self::$staticSanitizeCache[$dbname])){
return self::$staticSanitizeCache[$dbname];
}
$sanitized = preg_replace("/[^A-Za-z0-9' -]/", '', $dbname);
self::$staticSanitizeCache[$dbname] = $sanitized;
return $sanitized;
}
/**
* hash to db name for security
* Uses instance-level caching + persistent cache to avoid expensive PBKDF2 recomputation
* v3.0.0 optimization: Loads from persistent cache on first access
*/
private function hashDBName($dbname){
// Check memory cache first (fastest)
if(isset($this->hashCache[$dbname])){
return $this->hashCache[$dbname];
}
// Load from persistent cache if not loaded yet
$this->loadPersistentHashCache();
if(isset($this->hashCache[$dbname])){
return $this->hashCache[$dbname];
}
// Compute PBKDF2 hash (expensive: 1000 iterations)
$hash = hash_pbkdf2("sha256", $dbname, $this->secretKey, 1000, 20);
$this->hashCache[$dbname] = $hash;
$this->hashCacheDirty = true;
return $hash;
}
// ==========================================
// ATOMIC FILE OPERATIONS
// ==========================================
/**
* Atomically read a file with shared lock
* Prevents reading while another process is writing
*
* @param string $path File path
* @param mixed $default Default value if file doesn't exist
* @return mixed Decoded JSON data or default value
*/
private function atomicRead($path, $default = null){
clearstatcache(true, $path);
if(!file_exists($path)){
return $default;
}
$fp = fopen($path, 'rb');
if($fp === false){
return $default;
}
$startTime = microtime(true);
$locked = false;
// Try to acquire shared lock with timeout
while(!$locked && (microtime(true) - $startTime) < $this->lockTimeout){
$locked = flock($fp, LOCK_SH | LOCK_NB);
if(!$locked){
usleep($this->lockRetryDelay);
}
}
if(!$locked){
// Fallback: blocking lock as last resort
$locked = flock($fp, LOCK_SH);
}
if(!$locked){
fclose($fp);
return $default;
}
try {
$content = stream_get_contents($fp);
if($content === false || $content === ''){
return $default;
}
$data = json_decode($content, true);
// Check for JSON decode errors (corrupted data)
if($data === null && json_last_error() !== JSON_ERROR_NONE){
return null; // Return null for corrupted JSON, not default
}
return $data !== null ? $data : $default;
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
}
/**
* Fast atomic read optimized for index files
* v3.0.0 optimization: Skips clearstatcache and retry loop
* - Safe for index files that are read more often than written
* - Uses direct blocking lock instead of retry loop
*
* @param string $path File path
* @param mixed $default Default value if file doesn't exist
* @return mixed Decoded JSON data or default value
*/
private function atomicReadFast($path, $default = null){
// Skip clearstatcache - safe for cached index paths
if(!file_exists($path)){
return $default;
}
$fp = @fopen($path, 'rb');
if($fp === false){
return $default;
}
// Direct blocking LOCK_SH - faster than retry loop for read-heavy workloads
if(!flock($fp, LOCK_SH)){
fclose($fp);
return $default;
}
$content = stream_get_contents($fp);
flock($fp, LOCK_UN);
fclose($fp);
if($content === false || $content === ''){
return $default;
}
$data = json_decode($content, true);
return $data !== null ? $data : $default;
}
/**
* Atomically write a file with exclusive lock
*
* @param string $path File path
* @param mixed $data Data to write (will be JSON encoded)
* @param bool $prettyPrint Use JSON_PRETTY_PRINT
* @return bool Success
*/
private function atomicWrite($path, $data, $prettyPrint = false){
// Ensure directory exists
$dir = dirname($path);
if(!is_dir($dir)){
mkdir($dir, 0755, true);
}
$fp = fopen($path, 'cb'); // Create if not exists, open for writing
if($fp === false){
return false;
}
$startTime = microtime(true);
$locked = false;
// Try to acquire exclusive lock with timeout
while(!$locked && (microtime(true) - $startTime) < $this->lockTimeout){
$locked = flock($fp, LOCK_EX | LOCK_NB);
if(!$locked){
usleep($this->lockRetryDelay);
}
}
if(!$locked){
// Fallback: blocking lock as last resort
$locked = flock($fp, LOCK_EX);
}
if(!$locked){
fclose($fp);
return false;
}
try {
ftruncate($fp, 0);
rewind($fp);
$json = $prettyPrint
? json_encode($data, JSON_PRETTY_PRINT)
: json_encode($data);
$written = fwrite($fp, $json);
fflush($fp);
return $written !== false;
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
}
/**
* Atomically modify a file: read, apply callback, write
* This is the key method that prevents race conditions
*
* @param string $path File path
* @param callable $modifier Function that receives current data and returns modified data
* @param mixed $default Default value if file doesn't exist
* @param bool $prettyPrint Use JSON_PRETTY_PRINT for output
* @return array ['success' => bool, 'data' => modified data, 'error' => string|null]
*/
private function atomicModify($path, callable $modifier, $default = null, $prettyPrint = false){
// Ensure directory exists
$dir = dirname($path);
if(!is_dir($dir)){
mkdir($dir, 0755, true);
}
// Open with c+ mode: read/write, create if not exists
$fp = fopen($path, 'c+b');
if($fp === false){
return ['success' => false, 'data' => null, 'error' => 'Failed to open file'];
}
$startTime = microtime(true);
$locked = false;
// Try to acquire exclusive lock with timeout
while(!$locked && (microtime(true) - $startTime) < $this->lockTimeout){
$locked = flock($fp, LOCK_EX | LOCK_NB);
if(!$locked){
usleep($this->lockRetryDelay);
}
}
if(!$locked){
// Fallback: blocking lock as last resort
$locked = flock($fp, LOCK_EX);
}
if(!$locked){
fclose($fp);
return ['success' => false, 'data' => null, 'error' => 'Failed to acquire lock'];
}
try {
// Read current content while holding lock
clearstatcache(true, $path);
$size = filesize($path);
if($size === false || $size === 0){
$currentData = $default;
} else {
rewind($fp);
$content = fread($fp, $size);
$currentData = ($content !== false && $content !== '')
? json_decode($content, true)
: $default;
if($currentData === null && $content !== 'null'){
$currentData = $default;
}
}
// Apply modification
$newData = $modifier($currentData);
// Write modified data
ftruncate($fp, 0);
rewind($fp);
$json = $prettyPrint
? json_encode($newData, JSON_PRETTY_PRINT)
: json_encode($newData);
$written = fwrite($fp, $json);
fflush($fp);
if($written === false){
return ['success' => false, 'data' => null, 'error' => 'Failed to write data'];
}
return ['success' => true, 'data' => $newData, 'error' => null];
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
}
// ==========================================
// SHARDING HELPER METHODS
// ==========================================
/**
* Get the file path for a specific shard
* @param string $dbname
* @param int $shardId
* @return string
*/
private function getShardPath($dbname, $shardId){
$dbname = $this->sanitizeDbName($dbname);
$hash = $this->hashDBName($dbname);
return $this->dbDir . $hash . "-" . $dbname . "_s" . $shardId . ".nonedb";
}
/**
* Get the meta file path for a database
* @param string $dbname
* @return string
*/
private function getMetaPath($dbname){
$dbname = $this->sanitizeDbName($dbname);
$hash = $this->hashDBName($dbname);
return $this->dbDir . $hash . "-" . $dbname . ".nonedb.meta";
}
/**
* Check if a database is sharded
* @param string $dbname
* @return bool
*/
private function isSharded($dbname){
$dbname = $this->sanitizeDbName($dbname);
// Check cache first
if(isset($this->shardedCache[$dbname])){
return $this->shardedCache[$dbname];
}
// Use file_exists directly - shardedCache handles caching
$result = file_exists($this->getMetaPath($dbname));
$this->shardedCache[$dbname] = $result;
return $result;
}
private function invalidateShardedCache($dbname){
$dbname = $this->sanitizeDbName($dbname);
unset($this->shardedCache[$dbname]);
}
/**
* Read shard metadata with atomic locking
* @param string $dbname
* @return array|null
*/
private function readMeta($dbname){
$dbname = $this->sanitizeDbName($dbname);
$path = $this->getMetaPath($dbname);
return $this->atomicRead($path, null);
}
/**
* Get cached meta data with TTL support
* Avoids repeated file reads for frequently accessed meta
* @param string $dbname
* @param bool $forceRefresh Force refresh from disk
* @return array|null
*/
private function getCachedMeta($dbname, $forceRefresh = false){
$dbname = $this->sanitizeDbName($dbname);
$now = time();
if(!$forceRefresh && isset($this->metaCache[$dbname])){
$cacheAge = $now - ($this->metaCacheTime[$dbname] ?? 0);
if($cacheAge < $this->metaCacheTTL){
return $this->metaCache[$dbname];
}
}
$meta = $this->readMeta($dbname);
if($meta !== null){
$this->metaCache[$dbname] = $meta;
$this->metaCacheTime[$dbname] = $now;
}
return $meta;
}
/**
* Invalidate meta cache for a database
* @param string $dbname
*/
private function invalidateMetaCache($dbname){
$dbname = $this->sanitizeDbName($dbname);
unset($this->metaCache[$dbname]);
unset($this->metaCacheTime[$dbname]);
}
/**
* Write shard metadata with atomic locking
* @param string $dbname
* @param array $meta
* @return bool
*/
private function writeMeta($dbname, $meta){
$dbname = $this->sanitizeDbName($dbname);
$path = $this->getMetaPath($dbname);
$result = $this->atomicWrite($path, $meta, true);
if($result){
$this->invalidateMetaCache($dbname);
}
return $result;
}
/**
* Atomically modify shard metadata
* @param string $dbname
* @param callable $modifier
* @return array ['success' => bool, 'data' => modified meta, 'error' => string|null]
*/
private function modifyMeta($dbname, callable $modifier){
$dbname = $this->sanitizeDbName($dbname);
$path = $this->getMetaPath($dbname);
$result = $this->atomicModify($path, $modifier, null, true);
if($result['success']){
$this->invalidateMetaCache($dbname);
}
return $result;
}
/**
* Get data from a specific shard with atomic locking
* Auto-migrates to JSONL format if needed (v3.0.0)
* @param string $dbname
* @param int $shardId
* @return array Returns {"data": [...]} format for backward compatibility
*/
private function getShardData($dbname, $shardId){
$path = $this->getShardPath($dbname, $shardId);
// Ensure JSONL format (auto-migrate v2 if needed)
$this->ensureJsonlFormat($dbname, $shardId);
$jsonlIndex = $this->readJsonlIndex($dbname, $shardId);
if($jsonlIndex === null){
return array("data" => []);
}
// Read all records from JSONL
$allRecords = $this->readAllJsonl($path, $jsonlIndex);
// Convert to {"data": [...]} format where array index is local key
$data = [];
foreach($allRecords as $record){
if($record !== null && isset($record['key'])){
$localKey = $record['key'] % $this->shardSize;
$data[$localKey] = $record;
}
}
return array("data" => $data);
}
/**
* Write data to a specific shard with atomic locking
* @param string $dbname
* @param int $shardId
* @param array $data
* @return bool
*/
private function writeShardData($dbname, $shardId, $data){
$path = $this->getShardPath($dbname, $shardId);
return $this->atomicWrite($path, $data);
}
/**
* Atomically modify shard data
* @param string $dbname
* @param int $shardId
* @param callable $modifier
* @return array ['success' => bool, 'data' => modified data, 'error' => string|null]
*/
private function modifyShardData($dbname, $shardId, callable $modifier){
$path = $this->getShardPath($dbname, $shardId);
return $this->atomicModify($path, $modifier, array("data" => []));
}
// ==========================================
// PRIMARY KEY INDEX SYSTEM (v2.3.0)
// ==========================================
/**
* Get path to index file for a database
* Index provides O(1) key lookups instead of O(n) shard scans
* @param string $dbname
* @return string
*/
private function getIndexPath($dbname){
$dbname = $this->sanitizeDbName($dbname);
$hash = $this->hashDBName($dbname);
return $this->dbDir . $hash . "-" . $dbname . ".nonedb.idx";
}
/**
* Read index file with caching
* @param string $dbname
* @return array|null
*/
private function readIndex($dbname){
$dbname = $this->sanitizeDbName($dbname);
// Check runtime cache first
if(isset($this->indexCache[$dbname])){
return $this->indexCache[$dbname];
}
$path = $this->getIndexPath($dbname);
$index = $this->atomicRead($path, null);
if($index !== null){
$this->indexCache[$dbname] = $index;
}
return $index;
}
/**
* Write index file and update cache
* @param string $dbname
* @param array $index
* @return bool
*/
private function writeIndex($dbname, $index){
$dbname = $this->sanitizeDbName($dbname);
$index['updated'] = time();
$path = $this->getIndexPath($dbname);
$result = $this->atomicWrite($path, $index, false);
if($result){
$this->indexCache[$dbname] = $index;
}
return $result;
}
/**
* Invalidate index cache
* @param string $dbname
*/
private function invalidateIndexCache($dbname){
$dbname = $this->sanitizeDbName($dbname);
unset($this->indexCache[$dbname]);
}
/**
* Build index from existing database data
* Called automatically on first key-based lookup if index doesn't exist
* @param string $dbname
* @return array|null
*/
private function buildIndex($dbname){
$dbname = $this->sanitizeDbName($dbname);
$index = [
'version' => 1,
'created' => time(),
'updated' => time(),
'totalRecords' => 0,
'entries' => []
];
if($this->isSharded($dbname)){
$meta = $this->getCachedMeta($dbname);
if($meta === null){