radisk2.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. ;(function(){
  2. console.log("RADISK 2!!!!");
  3. function Radisk(opt){
  4. opt = opt || {};
  5. opt.log = opt.log || console.log;
  6. opt.file = String(opt.file || 'radata');
  7. var has = (Radisk.has || (Radisk.has = {}))[opt.file];
  8. if(has){ return has }
  9. opt.pack = opt.pack || (opt.memory? (opt.memory * 1000 * 1000) : 1399000000) * 0.3; // max_old_space_size defaults to 1400 MB.
  10. opt.until = opt.until || opt.wait || 250;
  11. opt.batch = opt.batch || (10 * 1000);
  12. opt.chunk = opt.chunk || (1024 * 1024 * 1); // 1MB
  13. opt.code = opt.code || {};
  14. opt.code.from = opt.code.from || '!';
  15. //opt.jsonify = true; // TODO: REMOVE!!!!
  16. function ename(t){ return encodeURIComponent(t).replace(/\*/g, '%2A') }
  17. function atomic(v){ return u !== v && (!v || 'object' != typeof v) }
  18. var map = Gun.obj.map;
  19. var LOG = false;
  20. if(!opt.store){
  21. return opt.log("ERROR: Radisk needs `opt.store` interface with `{get: fn, put: fn (, list: fn)}`!");
  22. }
  23. if(!opt.store.put){
  24. return opt.log("ERROR: Radisk needs `store.put` interface with `(file, data, cb)`!");
  25. }
  26. if(!opt.store.get){
  27. return opt.log("ERROR: Radisk needs `store.get` interface with `(file, cb)`!");
  28. }
  29. if(!opt.store.list){
  30. //opt.log("WARNING: `store.list` interface might be needed!");
  31. }
  32. /*
  33. Any and all storage adapters should...
  34. 1. Because writing to disk takes time, we should batch data to disk. This improves performance, and reduces potential disk corruption.
  35. 2. If a batch exceeds a certain number of writes, we should immediately write to disk when physically possible. This caps total performance, but reduces potential loss.
  36. */
  37. var r = function(key, val, cb){
  38. key = ''+key;
  39. if(val instanceof Function){
  40. var o = cb || {};
  41. cb = val;
  42. val = r.batch(key);
  43. if(u !== val){
  44. cb(u, r.range(val, o), o);
  45. if(atomic(val)){ return }
  46. // if a node is requested and some of it is cached... the other parts might not be.
  47. }
  48. if(r.thrash.at){
  49. val = r.thrash.at(key);
  50. if(u !== val){
  51. cb(u, r.range(val, o), o);
  52. if(atomic(val)){ cb(u, val, o); return }
  53. // if a node is requested and some of it is cached... the other parts might not be.
  54. }
  55. }
  56. return r.read(key, cb, o);
  57. }
  58. r.batch(key, val);
  59. if(cb){ r.batch.acks.push(cb) }
  60. if(++r.batch.ed >= opt.batch){ return r.thrash() } // (2)
  61. if(r.batch.to){ return }
  62. //clearTimeout(r.batch.to); // (1) // THIS LINE IS EVIL! NEVER USE IT! ALSO NEVER DELETE THIS SO WE NEVER MAKE THE SAME MISTAKE AGAIN!
  63. r.batch.to = setTimeout(r.thrash, opt.until || 1);
  64. }
  65. r.batch = Radix();
  66. r.batch.acks = [];
  67. r.batch.ed = 0;
  68. r.thrash = function(){
  69. var thrash = r.thrash;
  70. if(thrash.ing){ return thrash.more = true }
  71. thrash.more = false;
  72. thrash.ing = true;
  73. var batch = thrash.at = r.batch, i = 0;
  74. clearTimeout(r.batch.to);
  75. r.batch = null;
  76. r.batch = Radix();
  77. r.batch.acks = [];
  78. r.batch.ed = 0;
  79. //var id = Gun.text.random(2), S = (+new Date); console.log("<<<<<<<<<<<<", id);
  80. r.save(batch, function(err, ok){
  81. if(++i > 1){ opt.log('RAD ERR: Radisk has callbacked multiple times, please report this as a BUG at github.com/amark/gun/issues ! ' + i); return }
  82. if(err){ opt.log('err', err) }
  83. //console.log(">>>>>>>>>>>>", id, ((+new Date) - S), batch.acks.length);
  84. map(batch.acks, function(cb){ cb(err, ok) });
  85. thrash.at = null;
  86. thrash.ing = false;
  87. if(thrash.more){ thrash() }
  88. });
  89. }
  90. /*
  91. 1. Find the first radix item in memory.
  92. 2. Use that as the starting index in the directory of files.
  93. 3. Find the first file that is lexically larger than it,
  94. 4. Read the previous file to that into memory
  95. 5. Scan through the in memory radix for all values lexically less than the limit.
  96. 6. Merge and write all of those to the in-memory file and back to disk.
  97. 7. If file too large, split. More details needed here.
  98. */
  99. r.save = function(rad, cb){
  100. var s = function Span(){};
  101. s.find = function(tree, key){
  102. if(key < s.start){ return }
  103. s.start = key;
  104. r.list(s.lex);
  105. return true;
  106. }
  107. s.lex = function(file){
  108. file = (u === file)? u : decodeURIComponent(file);
  109. if(!file || file > s.start){
  110. s.mix(s.file || opt.code.from, s.start, s.end = file);
  111. return true;
  112. }
  113. s.file = file;
  114. }
  115. s.mix = function(file, start, end){
  116. s.start = s.end = s.file = u;
  117. r.parse(file, function(err, disk){
  118. if(err){ return cb(err) }
  119. disk = disk || Radix();
  120. Radix.map(rad, function(val, key){
  121. if(key < start){ return }
  122. if(end && end < key){ return s.start = key }
  123. // PLUGIN: consider adding HAM as an extra layer of protection
  124. disk(key, val); // merge batch[key] -> disk[key]
  125. });
  126. r.write(file, disk, s.next);
  127. });
  128. }
  129. s.next = function(err, ok){
  130. if(s.err = err){ return cb(err) }
  131. if(s.start){ return Radix.map(rad, s.find) }
  132. cb(err, ok);
  133. }
  134. Radix.map(rad, s.find);
  135. }
  136. /*
  137. Any storage engine at some point will have to do a read in order to write.
  138. This is true of even systems that use an append only log, if they support updates.
  139. Therefore it is unavoidable that a read will have to happen,
  140. the question is just how long you delay it.
  141. */
  142. r.write = function(file, rad, cb, o){
  143. o = ('object' == typeof o)? o : {force: o};
  144. var f = function Fractal(){};
  145. f.text = '';
  146. f.count = 0;
  147. f.file = file;
  148. f.each = function(val, key, k, pre){
  149. //console.log("RAD:::", JSON.stringify([val, key, k, pre]));
  150. if(u !== val){ f.count++ }
  151. if(opt.pack <= (val||'').length){ return cb("Record too big!"), true }
  152. var enc = Radisk.encode(pre.length) +'#'+ Radisk.encode(k) + (u === val? '' : ':'+ Radisk.encode(val)) +'\n';
  153. if((opt.chunk < f.text.length + enc.length) && (1 < f.count) && !o.force){
  154. f.text = '';
  155. f.limit = Math.ceil(f.count/2);
  156. f.count = 0;
  157. f.sub = Radix();
  158. Radix.map(rad, f.slice);
  159. return true;
  160. }
  161. f.text += enc;
  162. }
  163. f.write = function(){
  164. var tmp = ename(file);
  165. var start; LOG && (start = (+new Date)); // comment this out!
  166. opt.store.put(tmp, f.text, function(err){
  167. LOG && console.log("wrote JSON in", (+new Date) - start); // comment this out!
  168. if(err){ return cb(err) }
  169. r.list.add(tmp, cb);
  170. });
  171. }
  172. f.slice = function(val, key){
  173. if(key < f.file){ return }
  174. if(f.limit < (++f.count)){
  175. var name = f.file;
  176. f.file = key;
  177. f.count = 0;
  178. r.write(name, f.sub, f.next, o);
  179. return true;
  180. }
  181. f.sub(key, val);
  182. }
  183. f.next = function(err){
  184. if(err){ return cb(err) }
  185. f.sub = Radix();
  186. if(!Radix.map(rad, f.slice)){
  187. r.write(f.file, f.sub, cb, o);
  188. }
  189. }
  190. if(opt.jsonify){ return r.write.jsonify(f, file, rad, cb, o) } // temporary testing idea
  191. if(!Radix.map(rad, f.each, true)){ f.write() }
  192. }
  193. r.write.jsonify = function(f, file, rad, cb, o){
  194. var raw;
  195. var start; LOG && (start = (+new Date)); // comment this out!
  196. try{raw = JSON.stringify(rad.$);
  197. }catch(e){ return cb("Record too big!") }
  198. LOG && console.log("stringified JSON in", (+new Date) - start); // comment this out!
  199. if(opt.chunk < raw.length && !o.force){
  200. if(Radix.map(rad, f.each, true)){ return }
  201. }
  202. f.text = raw;
  203. f.write();
  204. }
  205. r.range = function(tree, o){
  206. if(!tree || !o){ return }
  207. if(u === o.start && u === o.end){ return tree }
  208. if(atomic(tree)){ return tree }
  209. var sub = Radix();
  210. Radix.map(tree, function(v,k){
  211. sub(k,v);
  212. }, o)
  213. return sub('');
  214. }
  215. ;(function(){
  216. var Q = {};
  217. r.read = function(key, cb, o){
  218. o = o || {};
  219. if(RAD && !o.next){ // cache
  220. var val = RAD(key);
  221. //if(u !== val){
  222. //cb(u, val, o);
  223. if(atomic(val)){ cb(u, val, o); return }
  224. // if a node is requested and some of it is cached... the other parts might not be.
  225. //}
  226. }
  227. o.span = (u !== o.start) || (u !== o.end);
  228. var g = function Get(){};
  229. g.lex = function(file){ var tmp;
  230. file = (u === file)? u : decodeURIComponent(file);
  231. tmp = o.next || key || (o.reverse? o.end || '\uffff' : o.start || '');
  232. if(!file || (o.reverse? file < tmp : file > tmp)){
  233. if(o.next || o.reverse){ g.file = file }
  234. if(tmp = Q[g.file]){
  235. tmp.push({key: key, ack: cb, file: g.file, opt: o});
  236. return true;
  237. }
  238. Q[g.file] = [{key: key, ack: cb, file: g.file, opt: o}];
  239. if(!g.file){
  240. g.it(null, u, {});
  241. return true;
  242. }
  243. r.parse(g.file, g.it);
  244. return true;
  245. }
  246. g.file = file;
  247. }
  248. g.it = function(err, disk, info){
  249. if(g.err = err){ opt.log('err', err) }
  250. g.info = info;
  251. if(disk){ RAD = g.disk = disk }
  252. disk = Q[g.file]; delete Q[g.file];
  253. map(disk, g.ack);
  254. }
  255. g.ack = function(as){
  256. if(!as.ack){ return }
  257. var tmp = as.key, o = as.opt, info = g.info, rad = g.disk || noop, data = r.range(rad(tmp), o), last = rad.last;
  258. o.parsed = (o.parsed || 0) + (info.parsed||0);
  259. o.chunks = (o.chunks || 0) + 1;
  260. if(!o.some){ o.some = (u !== data) }
  261. if(u !== data){ as.ack(g.err, data, o) }
  262. else if(!as.file){ !o.some && as.ack(g.err, u, o); return }
  263. if(!o.span){
  264. if(/*!last || */last === tmp){ !o.some && as.ack(g.err, u, o); return }
  265. if(last && last > tmp && 0 != last.indexOf(tmp)){ !o.some && as.ack(g.err, u, o); return }
  266. }
  267. if(o.some && o.parsed >= o.limit){ return }
  268. o.next = as.file;
  269. r.read(tmp, as.ack, o);
  270. }
  271. if(o.reverse){ g.lex.reverse = true }
  272. r.list(g.lex);
  273. }
  274. }());
  275. ;(function(){
  276. /*
  277. Let us start by assuming we are the only process that is
  278. changing the directory or bucket. Not because we do not want
  279. to be multi-process/machine, but because we want to experiment
  280. with how much performance and scale we can get out of only one.
  281. Then we can work on the harder problem of being multi-process.
  282. */
  283. var Q = {}, s = String.fromCharCode(31);
  284. r.parse = function(file, cb, raw){ var q;
  285. if(q = Q[file]){ return q.push(cb) } q = Q[file] = [cb];
  286. var p = function Parse(){}, info = {};
  287. p.disk = Radix();
  288. p.read = function(err, data){ var tmp;
  289. delete Q[file];
  290. if((p.err = err) || (p.not = !data)){
  291. return map(q, p.ack);
  292. }
  293. if(typeof data !== 'string'){
  294. try{
  295. if(opt.pack <= data.length){
  296. p.err = "Chunk too big!";
  297. } else {
  298. data = data.toString(); // If it crashes, it crashes here. How!?? We check size first!
  299. }
  300. }catch(e){ p.err = e }
  301. if(p.err){ return map(q, p.ack) }
  302. }
  303. info.parsed = data.length;
  304. var start; LOG && (start = (+new Date)); // keep this commented out in production!
  305. if(opt.jsonify){ // temporary testing idea
  306. try{
  307. var json = JSON.parse(data);
  308. p.disk.$ = json;
  309. LOG && console.log('parsed JSON in', (+new Date) - start); // keep this commented out in production!
  310. map(q, p.ack);
  311. return;
  312. }catch(e){ tmp = e }
  313. if('{' === data[0]){
  314. p.err = tmp || "JSON error!";
  315. return map(q, p.ack);
  316. }
  317. }
  318. var start; LOG && (start = (+new Date)); // keep this commented out in production!
  319. var tmp = p.split(data), pre = [], i, k, v, at, ats=[];
  320. if(!tmp || 0 !== tmp[1]){
  321. p.err = "File '"+file+"' does not have root radix! ";
  322. return map(q, p.ack);
  323. }
  324. while(tmp){
  325. k = v = u;
  326. i = tmp[1];
  327. tmp = p.split(tmp[2])||'';
  328. if('#' == tmp[0]){
  329. k = tmp[1];
  330. pre = pre.slice(0,i);
  331. if(i <= pre.length){
  332. pre.push(k);
  333. }
  334. }
  335. tmp = p.split(tmp[2])||'';
  336. if('\n' == tmp[0]){
  337. at = ats[i] || p.disk.at;
  338. p.disk(k, u, at);
  339. ats[i] = p.disk.at;
  340. ats[i+1] = p.disk.at[k] || (p.disk.at[k]={});
  341. continue;
  342. }
  343. if('=' == tmp[0] || ':' == tmp[0]){ v = tmp[1] }
  344. if(u !== k && u !== v){
  345. // p.disk(pre.join(''), v)// mark's code
  346. at = ats[i];// || p.disk.at;
  347. p.disk(k, v, at);
  348. ats[i] = p.disk.at;
  349. ats[i+1] = p.disk.at[k];
  350. }
  351. tmp = p.split(tmp[2]);
  352. }
  353. LOG && console.log('parsed JSON in', (+new Date) - start); // keep this commented out in production!
  354. //cb(err, p.disk);
  355. map(q, p.ack);
  356. };
  357. p.split = function(t){
  358. if(!t){ return }
  359. var l = [], o = {}, i = -1, a = '', b, c;
  360. i = t.indexOf(s);
  361. if(!t[i]){ return }
  362. a = t.slice(0, i);
  363. l[0] = a;
  364. l[1] = b = Radisk.decode(t.slice(i), o);
  365. l[2] = t.slice(i + o.i);
  366. return l;
  367. }
  368. p.ack = function(cb){
  369. if(!cb){ return }
  370. if(p.err || p.not){ return cb(p.err, u, info) }
  371. cb(u, p.disk, info);
  372. }
  373. if(raw){ return p.read(null, raw) }
  374. opt.store.get(ename(file), p.read);
  375. }
  376. }());
  377. ;(function(){
  378. var dir, q, f = String.fromCharCode(28), ef = ename(f);
  379. r.list = function(cb){
  380. if(dir){
  381. var tmp = {reverse: (cb.reverse)? 1 : 0};
  382. Radix.map(dir, function(val, key){
  383. return cb(key);
  384. }, tmp) || cb();
  385. return;
  386. }
  387. if(q){ return q.push(cb) } q = [cb];
  388. r.parse(f, r.list.init);
  389. }
  390. r.list.add = function(file, cb){
  391. var has = dir(file);
  392. if(has || file === ef){
  393. return cb(u, 1);
  394. }
  395. dir(file, true);
  396. cb.listed = (cb.listed || 0) + 1;
  397. r.write(f, dir, function(err, ok){
  398. if(err){ return cb(err) }
  399. cb.listed = (cb.listed || 0) - 1;
  400. if(cb.listed !== 0){ return }
  401. cb(u, 1);
  402. }, true);
  403. }
  404. r.list.init = function(err, disk){
  405. if(err){
  406. opt.log('list', err);
  407. setTimeout(function(){ r.parse(f, r.list.init) }, 1000);
  408. return;
  409. }
  410. if(disk){
  411. r.list.drain(disk);
  412. return;
  413. }
  414. if(!opt.store.list){
  415. r.list.drain(Radix());
  416. return;
  417. }
  418. // import directory.
  419. opt.store.list(function(file){
  420. dir = dir || Radix();
  421. if(!file){ return r.list.drain(dir) }
  422. r.list.add(file, noop);
  423. });
  424. }
  425. r.list.drain = function(rad, tmp){
  426. r.list.dir = dir = rad;
  427. tmp = q; q = null;
  428. Gun.list.map(tmp, function(cb){
  429. r.list(cb);
  430. });
  431. }
  432. }());
  433. var noop = function(){}, RAD, u;
  434. Radisk.has[opt.file] = r;
  435. return r;
  436. }
  437. ;(function(){
  438. var _ = String.fromCharCode(31), u;
  439. Radisk.encode = function(d, o, s){ s = s || _;
  440. var t = s, tmp;
  441. if(typeof d == 'string'){
  442. var i = d.indexOf(s);
  443. while(i != -1){ t += s; i = d.indexOf(s, i+1) }
  444. return t + '"' + d + s;
  445. } else
  446. if(d && d['#'] && (tmp = Gun.val.link.is(d))){
  447. return t + '#' + tmp + t;
  448. } else
  449. if(Gun.num.is(d)){
  450. return t + '+' + (d||0) + t;
  451. } else
  452. if(null === d){
  453. return t + ' ' + t;
  454. } else
  455. if(true === d){
  456. return t + '+' + t;
  457. } else
  458. if(false === d){
  459. return t + '-' + t;
  460. }// else
  461. //if(binary){}
  462. }
  463. Radisk.decode = function(t, o, s){ s = s || _;
  464. var d = '', i = -1, n = 0, c, p;
  465. if(s !== t[0]){ return }
  466. while(s === t[++i]){ ++n }
  467. p = t[c = n] || true;
  468. while(--n >= 0){ i = t.indexOf(s, i+1) }
  469. if(i == -1){ i = t.length }
  470. d = t.slice(c+1, i);
  471. if(o){ o.i = i+1 }
  472. if('"' === p){
  473. return d;
  474. } else
  475. if('#' === p){
  476. return Gun.val.link.ify(d);
  477. } else
  478. if('+' === p){
  479. if(0 === d.length){
  480. return true;
  481. }
  482. return parseFloat(d);
  483. } else
  484. if(' ' === p){
  485. return null;
  486. } else
  487. if('-' === p){
  488. return false;
  489. }
  490. }
  491. }());
  492. if(typeof window !== "undefined"){
  493. var Gun = window.Gun;
  494. var Radix = window.Radix;
  495. window.Radisk = Radisk;
  496. } else {
  497. var Gun = require('../gun');
  498. var Radix = require('./radix2');
  499. try{ module.exports = Radisk }catch(e){}
  500. }
  501. Radisk.Radix = Radix;
  502. }());