forked from holepunchto/pear
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidecar.js
More file actions
89 lines (72 loc) · 2.4 KB
/
sidecar.js
File metadata and controls
89 lines (72 loc) · 2.4 KB
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
'use strict'
const Localdrive = require('localdrive')
const Corestore = require('corestore')
const Hyperdrive = require('hyperdrive')
const HypercoreID = require('hypercore-id-encoding')
const subsystem = require('./lib/subsystem.js')
const crasher = require('./lib/crasher')
const {
SWAP,
PLATFORM_CORESTORE,
CHECKOUT,
LOCALDEV,
UPGRADE_LOCK,
PLATFORM_DIR,
WAKEUP
} = require('./lib/constants.js')
const registerUrlHandler = require('./lib/url-handler')
const parse = require('./lib/parse')
const { verbose } = parse.args(Bare.argv, { boolean: ['verbose'] })
crasher('sidecar', SWAP)
module.exports = bootSidecar().then(() => {
if (verbose) console.log('- Sidecar booted')
}).catch((err) => {
console.error(err.stack)
Bare.exit(1)
})
async function bootSidecar () {
const corestore = new Corestore(PLATFORM_CORESTORE, { manifestVersion: 1, compat: false })
await corestore.ready()
const drive = await createPlatformDrive()
const Sidecar = await subsystem(drive, '/subsystems/sidecar.js')
const updater = createUpdater()
const sidecar = new Sidecar({ updater, drive, corestore })
await sidecar.ready()
registerUrlHandler(WAKEUP)
function createUpdater () {
if (LOCALDEV) return null
const { checkout, swap } = getUpgradeTarget()
const updateDrive = checkout === CHECKOUT || HypercoreID.normalize(checkout.key) === CHECKOUT.key
? drive
: new Hyperdrive(corestore.session(), checkout.key)
return new Sidecar.Updater(updateDrive, { directory: PLATFORM_DIR, swap, lock: UPGRADE_LOCK, checkout })
}
async function createPlatformDrive () {
if (LOCALDEV) return new Localdrive(SWAP)
const drive = new Hyperdrive(corestore.session(), CHECKOUT.key)
const checkout = drive.checkout(CHECKOUT.length)
await checkout.ready()
checkout.on('close', () => drive.close())
return checkout
}
}
function getUpgradeTarget () {
if (LOCALDEV) return { checkout: CHECKOUT, swap: SWAP }
let key = null
for (let i = 0; i < Bare.argv.length; i++) {
const arg = Bare.argv[i]
if (arg.startsWith('--key=')) {
key = HypercoreID.normalize(arg.slice(6))
break
}
if (arg === '--key' && Bare.argv.length > i + 1) {
key = HypercoreID.normalize(Bare.argv[i + 1])
break
}
}
if (key === null || key === CHECKOUT.key) return { checkout: CHECKOUT, swap: SWAP }
return {
checkout: { key, length: 0, fork: 0 },
swap: null
}
}