-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
225 lines (217 loc) · 6.62 KB
/
index.js
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
console.log("\n\n####################")
console.log("#")
console.log("# Welcome to Planaria")
console.log("#")
console.log("####################\n\n")
// ENV
const fs = require('fs')
const path = require('path');
const dotenv = require('dotenv')
const mkdir = require('make-dir')
dotenv.config({path: path.resolve(process.cwd(), 'planaria.env')})
console.log("####################")
console.log("# ENV...")
console.log("#", JSON.stringify(process.env, null, 2))
console.log("#")
try {
const override = dotenv.parse(fs.readFileSync('child.env'))
for (let k in override) {
process.env[k] = override[k]
console.log("# Overriding", k, ":", override[k])
}
} catch (e) { }
console.log("# Final Planaria ENV:")
console.log("#", JSON.stringify(process.env, null, 2))
console.log("####################")
// Filter the folders in the current directory that has:
// 1. has planaria.js
// 2. the planaria.js file is valid
// 3. assign them to GENES
var GENES = []
var currentPath = process.cwd()
var genePath = currentPath + "/genes"
var dirs = fs.readdirSync(genePath).filter(function (file) {
return fs.statSync(genePath+'/'+file).isDirectory();
});
dirs.forEach(function(_path) {
let pth = genePath + "/" + _path
console.log("Reading", pth)
fs.readdirSync(pth).forEach(function(file) {
if (file === 'planaria.js') {
let f = require(pth + "/" + file)
if (f) {
console.log("Found planaria.js")
GENES.push(f)
} else {
console.log("planaria.js Not found")
}
}
})
})
console.log("GENES = ", GENES)
const Info = require('./info.js')
const Bit = require('./bit.js')
const Db = require('./db')
const daemon = {
run: async function() {
// 1. Initialize
await Db.init(GENES)
await Bit.init(Db, Info, GENES)
// Use the most recent block height-1 if "from" doesnt exist
// (because it starts crawling from clock+1)
let height = await Bit.request.height()
GENES.forEach(function(gene) {
if (gene.from === null || typeof gene.from === 'undefined') {
gene.from = height-1
}
})
await Info.init(GENES)
// 2. Index
console.log('Indexing...', new Date())
console.time('Indexing Keys')
await Db.index()
console.timeEnd('Indexing Keys')
// 3. Rewind
for(let i=0; i<GENES.length; i++) {
let gene = GENES[i]
let clk = await Info.getclock(gene)
// rewind (onrestart) shouldn't be triggered the first time
// only trigger if the clock is larger than "from"
if (clk > gene.from) {
await util.rewind(gene, clk)
} else if (clk === gene.from-1) {
if (gene.oncreate) {
console.log("$ running oncreate = ", gene.oncreate, gene.address)
await mkdir('/fs/' + gene.address)
await mkdir('./public/assets/' + gene.address)
await gene.oncreate({
fs: { path: '/fs/' + gene.address }
})
}
}
}
// 4. Start synchronizing
console.log('Synchronizing...', new Date())
console.time('Initial Sync')
await Bit.run()
console.timeEnd('Initial Sync')
// 5. Start listening
Bit.listen()
}
}
const util = {
run: async function() {
await Info.init(GENES)
await Db.init(GENES)
let cmd = process.argv[2]
if (cmd === 'fix') {
// Fix all: node index --max-old-space-size=4096 fix 560000
// Fix one machine: node index --max-old-space-size=4096 fix 560000 [ADDR1]
// Fix multiple machines: node index --max-old-space-size=4096 fix 560000 [ADDR1],[ADDR2]
if (process.argv.length > 3) {
let from = parseInt(process.argv[3])
await Bit.init(Db, Info, GENES)
let addrs = null
if (process.argv.length > 4) {
addrs = process.argv[4].split(',')
}
// 2. Rewind
console.log("Rewinding Machines to", from)
for(let i=0; i<GENES.length; i++) {
let gene = GENES[i]
// there is no address specified, or if the gene address is included in the arg
if (!addrs || addrs.includes(gene.address)) {
// fix gene, starting from index "from"
console.log("Rewinding", gene.address)
await util.rewind(gene, from)
// set the clock for the selected genes to "from"
await Info.setclock(gene, from)
console.log("Rewind Finished for", gene.address)
}
}
console.log("All Rewinds Complete")
// 3. Start synchronizing
console.log('Synchronizing...', new Date())
console.time('Initial Sync')
await Bit.run()
console.timeEnd('Initial Sync')
// 4. Start listening
Bit.listen()
}
} else if (cmd === 'index') {
await Db.index()
process.exit()
}
},
/*
*
* "rewind" is an interface that Planaria node developers must implement
* in order to take care of rewinding and cleaning up in case of restarts
*
* "rewind to X" means rewind the state back to the last time when block X was successfully crawled.
*
* Takes:
* - gene: the gene object
* - from: the index to onrestart from
*
* Programmers must handle restart logic in "onrestart" which involves:
* 1. Deleting all the items after the clock.self.now point
* 2. Setting the clock to clock.self.now
*
*/
rewind: async function(gene, from) {
if (from < gene.from) {
// if trying to rewind past gene.from
// set 'from' as gene.from-1
from = gene.from-1
}
console.log('Restarting from index ', from)
let currentHeight = await Bit.request.height()
if (gene.onrestart) {
let MACHINE = {
state: {
create: function(o) {
return Db.create(Object.assign({address: gene.address}, o))
},
read: function(o) {
return Db.read(Object.assign({address: gene.address}, o))
},
update: function(o) {
return Db.update(Object.assign({address: gene.address}, o))
},
delete: function(o) {
return Db.delete(Object.assign({address: gene.address}, o))
},
},
clock: {
bitcoin: {
now: currentHeight,
},
self: {
now: from,
set: function(val) {
return Info.setclock(gene, val)
}
},
},
env: process.env,
assets: {
path: './public/assets/' + gene.address
},
fs: {
path: '/fs/' + gene.address
}
}
await gene.onrestart(MACHINE)
}
console.log('[finished]')
}
}
const start = async function() {
if (process.argv.length > 2) {
util.run()
} else {
daemon.run()
}
}
start()