-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepl.js
194 lines (173 loc) · 5.96 KB
/
repl.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
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import readline from 'node:readline'
import { createReadStream, readFileSync } from 'node:fs'
import { Readable } from 'node:stream'
import { randomInt, randomUUID } from 'node:crypto'
import chalk from 'chalk'
import luaJson from 'lua-json'
import AoLoader from '@permaweb/ao-loader'
const __dirname = dirname(fileURLToPath(import.meta.url))
const METERING_FORMAT = 'wasm64-unknown-emscripten-draft_2024_10_16-metering'
const WASM64_FORMAT = 'wasm64-unknown-emscripten-draft_2024_02_15'
function binaryStream (WASM_FILE) {
return Promise.resolve(Readable.toWeb(createReadStream(WASM_FILE)))
}
function toTable (obj) {
const t = luaJson.format({ ...obj, TagArray: obj.Tags }, { spaces: 0, eol: '', singleQuote: true })
/**
* HACK
*
* - remove 'return' from beginning
* - remove dangling commas before closing } in tables
*/
return t
.substring('return'.length)
.replace(/,}/g, '}')
}
async function trampoline (init) {
let result = init
while (typeof result === 'function') result = await result()
return result
}
function wasmResponse (stream) {
return new Response(stream, { headers: { 'Content-Type': 'application/wasm' } })
}
async function replWith ({ ASSIGNABLE, moduleFormat, stream, env }) {
if (moduleFormat === METERING_FORMAT) console.log(chalk.bgGreen('Using metering module format...'))
let messageCount = 0
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
async function maybeAllowAssignments (init) {
if (!ASSIGNABLE) return init
console.log(chalk.gray(`Adding assignable: '${ASSIGNABLE}'`))
const allowAllAssignmentsMessage = {
Id: 'allow-assignments',
Target: env.Process.Id,
From: env.Process.Owner,
Owner: env.Process.Owner,
'Block-Height': randomInt(1_000_000, 1_500_000),
Module: env.Module.Id,
Tags: [
{ name: 'Action', value: 'Eval' }
],
Data: `
ao.addAssignable('assignable', ${ASSIGNABLE})
`
}
const { Memory } = await handle(init, allowAllAssignmentsMessage, env)
return Memory
}
function createEval (line) {
let Action = 'Eval'
const tags = [
{ name: 'Message-Count', value: `${++messageCount}` }
]
if (line === 'sample-gql') {
console.log(chalk.blue('Initializing sample GraphQL Server...'))
console.log(chalk.blue([
'Example:',
'',
'Gql:resolve(\'query GetPerson ($id: ID!) { person (id: $id) { firstName, lastName, age, friends { firstName, age } } }\', { id = "id-2" })',
'Gql:resolve(\'query GetPeople { people { firstName, lastName } }\')'
].join('\n')))
const init = readFileSync(join(__dirname, 'server.lua'), 'utf-8')
line = init
} else if (line === 'gateway') {
console.log(chalk.green('Initializing Arweave GraphQL Gateway...'))
const init = readFileSync(join(__dirname, 'gateway.lua'), 'utf-8')
line = init
} else if (line.startsWith('query') || line.startsWith('mutation')) {
const [operation, variables] = line.split('|').map(l => l.trim())
Action = 'GraphQL.Operation'
tags.push({ name: 'Content-Type', value: 'application/json' })
tags.push({ name: 'Operation', value: operation })
line = variables ? JSON.stringify(JSON.parse(variables)) : '1234'
}
const id = randomUUID()
return {
Id: id,
Target: env.Process.Id,
From: env.Process.Owner,
Owner: env.Process.Owner,
Fee: randomInt(1_000_000, 1_500_000),
Quantity: randomInt(1_000_000, 1_500_000),
Reward: randomInt(1_000_000, 1_500_000),
'Block-Id': randomUUID(),
'Block-Height': randomInt(1_000_000, 1_500_000),
'Block-Timestamp': new Date().getTime(),
'Block-Previous': randomUUID(),
Module: env.Module.Id,
Tags: [
{ name: 'Action', value: Action },
...tags
],
Timestamp: new Date().getTime(),
Data: line
}
}
const handle = await WebAssembly.compileStreaming(wasmResponse(stream), { format: moduleFormat })
.then((module) => AoLoader(
(info, receiveInstance) => WebAssembly.instantiate(module, info).then(receiveInstance),
{
format: moduleFormat,
memoryLimit: '2-gb',
computeLimit: 9_000_000_000_000,
inputEncoding: 'JSON-1',
outputEncoding: 'JSON-1'
}
))
const repl = (memory) => new Promise((resolve, reject) =>
rl.question(
'aos-graphql' + '> ',
async function (line) {
if (line === 'exit') return resolve()
if (line.startsWith('msg-')) {
console.log(toTable(createEval(line.substring('msg-'.length))))
// prompt for next input into repl
return resolve(() => repl(memory))
}
try {
const message = createEval(line)
const { Memory, Messages, Output, Error } = await handle(memory, message, env)
if (Error) console.error(Error)
if (Output?.data) console.log(Output?.data)
if (Messages && Messages.length) Messages.forEach((m) => console.log(m))
// prompt for next input into repl
return resolve(() => repl(Memory))
} catch (err) {
console.error('Error: ', err)
reject(err)
}
}
)
)
return (init) => Promise.resolve(init)
.then(maybeAllowAssignments)
.then((init) => trampoline(() => repl(init)))
.finally(() => rl.close())
}
replWith({
/**
* Assignable that allows all assignments
*/
ASSIGNABLE: 'function (msg) return true end',
stream: await binaryStream(process.env.WASM_FILE || './process.sandbox.wasm'),
moduleFormat: process.env.MODULE_FORMAT || WASM64_FORMAT,
env: {
Process: {
Id: 'PROCESS_TEST',
Owner: randomUUID(),
Tags: [
{ name: 'Module', value: 'aos-graphql' }
]
},
Module: {
Id: 'MODULE_TEST',
Owner: randomUUID(),
Tags: []
}
}
}).then((start) => start(null))