Skip to content

Commit

Permalink
refactor modules library (#109)
Browse files Browse the repository at this point in the history
* refactor `modules` library

* add back shebang

* move dist tag to top of file
  • Loading branch information
juliangruber authored Apr 26, 2023
1 parent 746844c commit 94801cf
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 101 deletions.
1 change: 0 additions & 1 deletion commands/station.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export const station = async ({ json }) => {
FIL_WALLET_ADDRESS,
MAX_DISK_SPACE,
storagePath: join(paths.moduleCache, 'saturn-L2-node'),
binariesPath: paths.moduleBinaries,
metricsStream: await createMetricsStream('saturn-L2-node'),
activityStream: createActivityStream('Saturn'),
logStream: createLogStream(join(paths.moduleLogs, 'saturn-L2-node.log'))
Expand Down
94 changes: 94 additions & 0 deletions lib/modules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import * as os from 'node:os'
import assert from 'node:assert'
import { join } from 'node:path'
import { mkdir, chmod } from 'node:fs/promises'
import { fetch } from 'undici'
import { pipeline } from 'node:stream/promises'
import gunzip from 'gunzip-maybe'
import tar from 'tar-fs'
import unzip from 'unzip-stream'
import { once } from 'node:events'
import { createWriteStream } from 'node:fs'
import { paths } from './paths.js'

const { GITHUB_TOKEN } = process.env
const authorization = GITHUB_TOKEN ? `Bearer ${GITHUB_TOKEN}` : undefined

export const getBinaryModuleExecutable = ({
module,
executable
}) => {
return join(
paths.moduleBinaries,
module,
`${executable}${os.platform() === 'win32' ? '.exe' : ''}`
)
}

export const installBinaryModule = async ({
module,
repo,
distTag,
executable,
arch = os.arch(),
targets
}) => {
console.log(
`[${module}] GitHub client: ${authorization ? 'authorized' : 'anonymous'}`
)
const target = targets.find(target =>
target.platform === os.platform() && target.arch === arch
)
assert(target, `[${module}] Unsupported platform: ${os.platform()} ${arch}`)

await mkdir(paths.moduleBinaries, { recursive: true })
const outFile = join(paths.moduleBinaries, module)

console.log(`[${module}] ⇣ downloading ${os.platform()} ${arch}`)
const res = await fetch(
`https://github.com/${repo}/releases/download/${distTag}/${target.asset}`,
{
headers: {
...(authorization ? { authorization } : {})
},
redirect: 'follow'
}
)

if (res.status >= 300) {
throw new Error(
`[${module}] Cannot fetch binary ${os.platform()} ${arch}: ${res.status}\n` +
await res.text()
)
}

if (!res.body) {
throw new Error(
`[${module}] Cannot fetch binary ${os.platform()} ${arch}: no response body`
)
}

if (target.asset.endsWith('tar.gz')) {
await pipeline(res.body, gunzip(), tar.extract(outFile))
} else {
await mkdir(join(paths.moduleBinaries, module), { recursive: true })
const parser = unzip.Parse()
await Promise.all([
(async () => {
while (true) {
const [entry] =
/** @type {[UnzipStreamEntry]} */
(await once(parser, 'entry'))
if (entry.path === executable) {
const outPath = join(paths.moduleBinaries, module, executable)
await pipeline(entry, createWriteStream(outPath))
await chmod(outPath, 0o755)
return
}
}
})(),
pipeline(res.body, parser)
])
}
console.log(`[${module}] ✓ ${outFile}`)
}
33 changes: 24 additions & 9 deletions lib/saturn-node.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,44 @@
import timers from 'node:timers/promises'
import { execa } from 'execa'
import { join } from 'node:path'
import { arch, platform } from 'node:os'
import { fetch } from 'undici'
import * as Sentry from '@sentry/node'

const archOverwritten = platform() === 'darwin' ? 'x64' : arch()
import { installBinaryModule, getBinaryModuleExecutable } from './modules.js'

const DIST_TAG = 'v0.5.0'

export async function install () {
await installBinaryModule({
module: 'saturn-l2-node',
repo: 'filecoin-saturn/L2-node',
distTag: DIST_TAG,
executable: 'L2-node',
arch: platform() === 'darwin' ? 'x64' : arch(),
targets: [
{ platform: 'darwin', arch: 'x64', asset: 'L2-node_Darwin_x86_64.zip' },
{ platform: 'linux', arch: 'arm64', asset: 'L2-node_Linux_arm64.tar.gz' },
{ platform: 'linux', arch: 'ia32', asset: 'L2-node_Linux_i386.tar.gz' },
{ platform: 'linux', arch: 'x64', asset: 'L2-node_Linux_x86_64.tar.gz' },
{ platform: 'win32', arch: 'x64', asset: 'L2-node_Windows_x86_64.tar.gz' }
]
})
}

async function start ({
FIL_WALLET_ADDRESS,
MAX_DISK_SPACE,
storagePath,
binariesPath,
metricsStream,
activityStream,
logStream
}) {
logStream.write('Starting Saturn node')

const childProcess = execa(
join(
binariesPath,
`saturn-L2-node-${platform()}-${archOverwritten}`,
`saturn-L2-node${platform() === 'win32' ? '.exe' : ''}`
), {
getBinaryModuleExecutable({
module: 'saturn-l2-node',
executable: 'L2-node'
}), {
env: {
ROOT_DIR: storagePath,
FIL_WALLET_ADDRESS,
Expand Down
93 changes: 2 additions & 91 deletions scripts/post-install.js
Original file line number Diff line number Diff line change
@@ -1,94 +1,5 @@
#!/usr/bin/env node

import { fetch } from 'undici'
import { join, dirname } from 'node:path'
import { mkdir, chmod } from 'node:fs/promises'
import { createWriteStream } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { pipeline } from 'node:stream/promises'
import tar from 'tar-fs'
import gunzip from 'gunzip-maybe'
import unzip from 'unzip-stream'
import { once } from 'node:events'
import { platform, arch } from 'node:os'
import assert from 'node:assert'
import { install as installSaturn } from '../lib/saturn-node.js'

const SATURN_DIST_TAG = 'v0.5.0'
const githubToken = process.env.GITHUB_TOKEN
const authorization = githubToken ? `Bearer ${githubToken}` : undefined

console.log('GitHub client:', authorization ? 'authorized' : 'anonymous')

const targets = [
{ platform: 'darwin', arch: 'x64', url: 'Darwin_x86_64', archive: 'zip' },
{ platform: 'linux', arch: 'arm64', url: 'Linux_arm64', archive: 'tar.gz' },
{ platform: 'linux', arch: 'ia32', url: 'Linux_i386', archive: 'tar.gz' },
{ platform: 'linux', arch: 'x64', url: 'Linux_x86_64', archive: 'tar.gz' },
{ platform: 'win32', arch: 'x64', url: 'Windows_x86_64', archive: 'tar.gz' }
]

const archOverwritten = platform() === 'darwin' ? 'x64' : arch()
const target = targets.find(target =>
target.platform === platform() &&
target.arch === archOverwritten
)
assert(target, `Unsupported platform: ${platform} ${arch}`)

const outDir = join(
dirname(fileURLToPath(import.meta.url)),
'..',
'modules'
)
await mkdir(outDir, { recursive: true })

const outName = `saturn-L2-node-${platform()}-${archOverwritten}`
const outFile = join(outDir, outName)

console.log(' ⇣ downloading %s', outName)
const res = await fetch(
`https://github.com/filecoin-saturn/L2-node/releases/download/${SATURN_DIST_TAG}/L2-node_${target.url}.${target.archive}`,
{
headers: {
...(authorization ? { authorization } : {})
},
redirect: 'follow'
}
)

if (res.status >= 300) {
throw new Error(
`Cannot fetch saturn-l2 binary ${platform()} ${archOverwritten}: ${res.status}\n` +
await res.text()
)
}

if (!res.body) {
throw new Error(
`Cannot fetch saturn-l2 binary ${platform()} ${archOverwritten}: no response body`
)
}

if (target.archive === 'tar.gz') {
await pipeline(res.body, gunzip(), tar.extract(outFile))
} else {
await mkdir(join(outDir, outName), { recursive: true })
const parser = unzip.Parse()
await Promise.all([
(async () => {
while (true) {
const [entry] =
/** @type {[UnzipStreamEntry]} */
(await once(parser, 'entry'))
if (entry.path === 'L2-node') {
const outPath = join(outDir, outName, 'saturn-L2-node')
await pipeline(entry, createWriteStream(outPath))
await chmod(outPath, 0o755)
return
}
}
})(),
pipeline(res.body, parser)
])
}

console.log(' ✓ %s', outFile)
await installSaturn()

0 comments on commit 94801cf

Please sign in to comment.