-
Notifications
You must be signed in to change notification settings - Fork 3
/
machine.js
183 lines (158 loc) · 4.73 KB
/
machine.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
import { promises as fs } from 'fs'
import path from 'path'
import { nextTick } from 'process'
import { inspect } from 'util'
import { createRunner } from './runner.js'
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPLY_LIMIT = 2000
const defaultLogPath = path.join(__dirname, 'log.txt')
export function createMachine ({
logPath = defaultLogPath,
logging = true
} = {}) {
let runner = createRunner()
let commandBuffer = []
let isRunning = false
return {
getSystemState: () => runner.getSystemState(),
appendLoggable,
executeLoggable,
replayPast,
replayPastFromDisk,
getLogFromDisk,
flushCommands,
queue,
fork,
}
async function fork (opts = {}) {
// dont want to override the log
// theres prolly a different way to solve this
// like setting a different log file
if (opts.logging !== false) {
throw new Error('logging must be set to false')
}
const commands = await getLogFromDisk()
const clone = createMachine(opts)
await clone.replayPast(commands)
return clone
}
function queue (opts) {
commandBuffer.push(opts)
nextTick(flushCommands)
}
async function appendLoggable (loggable, msg) {
await fs.appendFile(logPath, createLogLine(loggable))
}
function createLogLine (loggable) {
return '\n' + JSON.stringify(loggable)
}
async function executeLoggable (loggable, msg) {
const { id, command } = loggable
console.log(command)
const { result, error } = await runner.runCommand(id, command)
return { result, error }
}
async function restart () {
await runner.close()
console.log('runner closed')
runner = createRunner()
console.log('new runner created', runner)
await replayPastFromDisk()
console.log('replayed past from disk')
commandBuffer = []
isRunning = false
}
async function getLogFromDisk () {
let logFile
try {
logFile = await fs.readFile(logPath, 'utf8')
} catch (err) {
if (err.code === 'ENOENT') {
console.log('No logfile found, starting new one.')
logFile = '{"id":"0","command":"0"}'
await fs.writeFile(logPath, logFile)
} else {
console.error(err)
throw err
}
}
const loggableCommands = logFile.split('\n').map((entry) => {
console.log(entry)
return JSON.parse(entry)
})
return loggableCommands
}
async function replayPastFromDisk () {
const loggableCommands = await getLogFromDisk()
await replayPast(loggableCommands)
}
async function replayPast (loggableCommands) {
isRunning = true
const results = []
for (const command of loggableCommands) {
const result = await executeLoggable(command)
console.log(`${command}:`)
console.log(result)
results.push(result)
}
isRunning = false
nextTick(flushCommands)
return results
}
async function flushCommands () {
// if we're already running, do nothing
if (isRunning) {
return
}
if (commandBuffer.length === 0) return
// handle next command
isRunning = true
const { loggable, msg } = commandBuffer.shift()
// Commit to running message
if (logging) {
console.log('append loggable: ', loggable)
await appendLoggable(loggable, msg)
}
let stringReply
const { result, error } = await executeLoggable(loggable)
stringReply = serializeReply({ error, result })
if (error && error.fatal) {
console.log('we have caught a fatal error')
console.error(error)
// If we can't execute that command, we need to purge it from the logs
// So that replays don't also throw crashing errors.
await strikeLastLog(loggable)
console.log('restarting')
await restart()
console.log('restarted')
stringReply = `Fatal Error, state reverted:\n${error.stack}`
}
if (stringReply.length > REPLY_LIMIT) {
const replyTruncactionMessage = `\n(reply truncated... length: ${stringReply.length})`
stringReply = stringReply.slice(0, REPLY_LIMIT - replyTruncactionMessage.length) + replyTruncactionMessage
}
console.log(`> ${stringReply}`)
if (!msg || !msg.reply) return
msg.reply(stringReply)
isRunning = false
// continue flushing on next tick
setTimeout(flushCommands)
}
async function strikeLastLog (loggable) {
if (!logging) {
return
}
const stringMessage = createLogLine(loggable)
const stat = await fs.stat(logPath)
await fs.truncate(logPath, stat.size - stringMessage.length)
}
}
function serializeReply ({ result, error }) {
const opts = { depth: 1 }
if (error) {
return `Error Thrown: ${inspect(error, opts)}`
} else {
return inspect(result, opts)
}
}