This commit is contained in:
srgooglo 2021-06-15 16:02:31 +02:00
parent 4432bf8535
commit dfb8735a15
5 changed files with 161 additions and 40 deletions

View File

@ -6,6 +6,7 @@ const fs = require('fs')
//* LIBS //* LIBS
const { objectToArrayMap } = require("@corenode/utils") const { objectToArrayMap } = require("@corenode/utils")
const TOKENIZER = require("./lib/tokenizer") const TOKENIZER = require("./lib/tokenizer")
const { websocket } = require("corenode").net
//* GLOBALS //* GLOBALS
const SERVER_REGISTRY = "server.registry" const SERVER_REGISTRY = "server.registry"
@ -143,6 +144,30 @@ function init() {
start() start()
} }
function startHeartbeatServer() {
const heartbeatServer = websocket.server.createInstance({
port: 1011,
onMessage: (connection, message) => {
setTimeout(() => {
const index = Number(message.utf8Data)
connection.send(index + 1)
}, 1000)
},
authorizeOrigin: (origin) => {
// await 5s to simulate an authorization process
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve(true)
}, 5000)
})
},
onClose: () => {
}
})
}
function start() { function start() {
//? set middlewares //? set middlewares
SERVER.use(express.json()) SERVER.use(express.json())
@ -170,6 +195,7 @@ function start() {
}) })
// TODO: set websocket server heap & events // TODO: set websocket server heap & events
startHeartbeatServer()
SERVER.get("/heartbeat", (req, res, next) => { SERVER.get("/heartbeat", (req, res, next) => {
res.json({ res.json({
uptime: getUptime() uptime: getUptime()

View File

@ -1,12 +1,53 @@
const express = require("express")
const { objectToArrayMap } = require("@corenode/utils")
const uuid = require("uuid") const uuid = require("uuid")
const os = require("os") const os = require("os")
const path = require("path")
const fs = require("fs")
const express = require("express")
const { objectToArrayMap } = require("@corenode/utils")
const { Controller } = require("@@classes") const SERVER_VERSION = global.SERVER_VERSION = runtime.helpers.getVersion()
const SERVER_GENFILE = "origin.server"
const SERVER_GENFILEPATH = path.resolve(process.cwd(), SERVER_GENFILE)
const IS_DEV = global.IS_DEV = runtime.helpers.isDevMode()
const { Controller } = require("@classes")
const { getLocalEndpoints, fetchController } = require("./lib/helpers") const { getLocalEndpoints, fetchController } = require("./lib/helpers")
const nethub = require("./lib/nethub") const nethub = require("./lib/nethub")
const SERVER_VERSION = global.SERVER_VERSION = runtime.helpers.getVersion() const TOKENIZER = require("./lib/tokenizer")
const GEN = {
stat: () => {
return fs.lstatSync(SERVER_GENFILEPATH)
},
get: (key) => {
let data = {}
if (fs.existsSync(SERVER_GENFILEPATH)) {
data = JSON.parse(fs.readFileSync(SERVER_GENFILEPATH, 'utf8'))
}
if (typeof key === "string") {
return data[key]
}
return data
},
write: (mutation) => {
let data = GEN.get()
data = { ...data, ...mutation }
GEN.data = data
return fs.writeFileSync(SERVER_GENFILEPATH, JSON.stringify(data, null, 2), { encoding: "utf-8" })
},
create: () => {
let data = {
created: Date.now(),
serverToken: TOKENIZER.generate()
}
GEN.write(data)
},
file: SERVER_GENFILE,
filepath: SERVER_GENFILEPATH,
}
const defaultMiddlewares = [ const defaultMiddlewares = [
require('cors')(), require('cors')(),
@ -45,6 +86,7 @@ class RequestServer {
// set server basics // set server basics
this.httpServer = require("express")() this.httpServer = require("express")()
this.usid = uuid.v5(os.hostname(), uuid.v4()) // unique session identifier this.usid = uuid.v5(os.hostname(), uuid.v4()) // unique session identifier
this.oid = GEN.get("serverToken")
this._everyRequest = null this._everyRequest = null
this._onRequest = {} this._onRequest = {}
@ -104,7 +146,28 @@ class RequestServer {
} }
init() { init() {
nethub.heartbeat() //? check if origin.server exists
if (!fs.existsSync(SERVER_GENFILEPATH)) {
GEN.create()
}
//? check origin.server integrity
const GENDATA = global.GENDATA = GEN.get()
const GENSTAT = global.GENSTAT = GEN.stat()
if (typeof GENDATA.created === "undefined") {
console.warn("Server generation file not contains an creation date")
GEN.write({ created: Date.parse(GENSTAT.birthtime) })
}
if (typeof GENDATA.serverToken === "undefined") {
console.warn("Missing server token!")
GEN.create()
}
//? set last start
GEN.write({ lastStart: Date.now() })
const localEndpoints = getLocalEndpoints() const localEndpoints = getLocalEndpoints()
this.httpServer.use(express.json()) this.httpServer.use(express.json())
@ -168,6 +231,7 @@ class RequestServer {
}) })
this.httpServer.listen(this.params.port, () => { this.httpServer.listen(this.params.port, () => {
nethub.registerOrigin({ entry: "/", oid: this.oid })
console.log(`✅ Ready on port ${this.params.port}!`) console.log(`✅ Ready on port ${this.params.port}!`)
}) })
} }

View File

@ -1,27 +1,46 @@
//* LIBRARIES
const axios = require('axios') const axios = require('axios')
const { websocket } = require('corenode').net
const NETHUB_URI = global.NETHUB_URI = "https://nethub.ragestudio.net" //* constables
const NETHUB_HOSTNAME = IS_DEV ? "localhost" : global.NETHUB_HOSTNAME = "nethub.ragestudio.net"
const axiosInstance = axios.create({ const nethubRequest = axios.create({
baseURL: NETHUB_URI baseURL: IS_DEV ? `http://localhost:1010` : `https://${NETHUB_HOSTNAME}`
}) })
function heartbeat(params) { //* HANDLERS
axiosInstance.get("heartbeat") const getHeartbeat = (...context) => nethubRequest.get("heartbeat", ...context)
const putRegistry = (...context) => nethubRequest.put("registry", ...context)
const getRegistry = (...context) => nethubRequest.get("registry", ...context)
const deleteRegistry = (...context) => nethubRequest.delete("registry", ...context)
function heartbeat() {
return new Promise((resolve, reject) => {
getHeartbeat()
.then((res) => { .then((res) => {
console.log(res.response.data) return resolve(res.data)
}) })
.catch((err) => { .catch((err) => {
console.log(err) runtime.logger.dump("error", err)
console.error(`❌ [${err.response?.status ?? "0"}] [${NETHUB_HOSTNAME}] Failed to listen heartbeat > ${err}`)
return reject(err)
})
}) })
} }
function registerOrigin() { async function registerOrigin(payload) {
putRegistry({ data: { ...payload } })
.then((res) => {
console.log(res.data)
})
.catch((err) => {
console.log(err.response.data)
})
} }
function getOrigin() { async function getOrigin() {
const hubData = await getRegistry()
console.log(hubData)
} }
module.exports = { heartbeat, registerOrigin, getOrigin } module.exports = { heartbeat, registerOrigin, getOrigin }

View File

@ -0,0 +1,12 @@
const { validate, version, v5, v4 } = require('uuid')
const os = require('os')
function generate(hostname) {
return v5(hostname ?? os.hostname(), v4())
}
function valid(uuid) {
return validate(uuid) && version(uuid) === 5
}
module.exports = { generate, valid }

View File

@ -910,10 +910,10 @@
"@babel/helper-validator-identifier" "^7.14.0" "@babel/helper-validator-identifier" "^7.14.0"
to-fast-properties "^2.0.0" to-fast-properties "^2.0.0"
"@corenode/builder@0.25.0": "@corenode/builder@0.25.1":
version "0.25.0" version "0.25.1"
resolved "https://registry.yarnpkg.com/@corenode/builder/-/builder-0.25.0.tgz#198ca7f453856afc84cb21873adf83c5406c00fc" resolved "https://registry.yarnpkg.com/@corenode/builder/-/builder-0.25.1.tgz#a79dc14a0f8ea3eca5515876a09c5db4b963a573"
integrity sha512-zjRd7xH7RlzNTgN1zsN1jCZTohLhTW5ItR8croNGa2mrrwijRRpl7TWhJOzIMASweEQvEhibRf3cblMvWm/ldg== integrity sha512-x4CyLr0sQ0eLgJWewOAzyYi8Tr7OFz/DNDV89nAj3wevUnMobT4tOzn7fal2mGGUp75Xkt1fW/UfUii/KIrtUw==
dependencies: dependencies:
"@babel/core" "^7.13.14" "@babel/core" "^7.13.14"
"@babel/plugin-proposal-class-properties" "7.13.0" "@babel/plugin-proposal-class-properties" "7.13.0"
@ -923,7 +923,7 @@
"@babel/preset-env" "7.13.12" "@babel/preset-env" "7.13.12"
"@babel/preset-typescript" "7.13.0" "@babel/preset-typescript" "7.13.0"
"@babel/runtime" "7.13.10" "@babel/runtime" "7.13.10"
"@corenode/utils" "0.25.0" "@corenode/utils" "0.25.1"
cli-progress "^3.9.0" cli-progress "^3.9.0"
map-stream "^0.0.7" map-stream "^0.0.7"
rimraf "^3.0.2" rimraf "^3.0.2"
@ -932,17 +932,17 @@
through2 "^4.0.2" through2 "^4.0.2"
vinyl-fs "^3.0.3" vinyl-fs "^3.0.3"
"@corenode/git-lib@0.25.0": "@corenode/git-lib@0.25.1":
version "0.25.0" version "0.25.1"
resolved "https://registry.yarnpkg.com/@corenode/git-lib/-/git-lib-0.25.0.tgz#b5e80090e2e179ec2b16930b34c2cd6f4ec56790" resolved "https://registry.yarnpkg.com/@corenode/git-lib/-/git-lib-0.25.1.tgz#93f475e4d22be20acdd82d191e58dbf748ffa1d1"
integrity sha512-7c8LmVbdvM8NvyFJDi+vju7FzbsNAVvQVcZajmNYwivizG/cyQWbmm6phToipMAP3BjTI2BuDQFzEPZKEtWgvA== integrity sha512-iv/nmu3cVh3ydBMyL8o47t2PTcvpLOYMECjdtjXBEQZ7ibH7l7NnLo4ZkpvzxXjrLc7ZW2yRTL+699tLYAR5fg==
dependencies: dependencies:
execa "^5.0.0" execa "^5.0.0"
"@corenode/utils@0.25.0": "@corenode/utils@0.25.1":
version "0.25.0" version "0.25.1"
resolved "https://registry.yarnpkg.com/@corenode/utils/-/utils-0.25.0.tgz#c6b0974a8e7b0556c9366e2677bd81b84528cd37" resolved "https://registry.yarnpkg.com/@corenode/utils/-/utils-0.25.1.tgz#841e4fd99aff9322a76d1364b3c05b09f56038a2"
integrity sha512-+lXEJqdwxLsT19vSTBTVMx18yj4WjLOTTKsJbUAn5AO6MbspJ8SSOuGESJB+ODumptybvvMOmwkF8vzu0ib1WA== integrity sha512-hSi6WMQCni0R8D8PA3nh3MIrZ6WRRz6lql/Gu+zy6tRLEMzX7F3fKmtCEGObzAX8YaMLpI98sshn5sJpmIODxQ==
dependencies: dependencies:
axios "^0.21.1" axios "^0.21.1"
chalk "^4.1.0" chalk "^4.1.0"
@ -1498,16 +1498,16 @@ core-util-is@~1.0.0:
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=
corenode@^0.25.0: corenode@^0.25.1:
version "0.25.0" version "0.25.1"
resolved "https://registry.yarnpkg.com/corenode/-/corenode-0.25.0.tgz#64410e427faaa6888e1e144c2790a815cb5ff6c7" resolved "https://registry.yarnpkg.com/corenode/-/corenode-0.25.1.tgz#f21f5d83ebdf2201dbca898610be0e3109aa5b11"
integrity sha512-7OK/LjuhJSgI2fljcnaSjWIbrTYrO2o6Z9XmsiORoCZHWvqJ9b0R9mJ//l/k9DrsDjDEyyKkFZQw7u+YLgoxZw== integrity sha512-kVgEIRFyNQ/uYg4QqUMrsttz8LVAQu+Dor1S7AE9UDZO+tgC12uq9mmNSvCX1QyZCl1NB6LwAU8fxHP6kqlhhg==
dependencies: dependencies:
"7zip-bin" "^5.1.1" "7zip-bin" "^5.1.1"
"@babel/runtime" "^7.13.10" "@babel/runtime" "^7.13.10"
"@corenode/builder" "0.25.0" "@corenode/builder" "0.25.1"
"@corenode/git-lib" "0.25.0" "@corenode/git-lib" "0.25.1"
"@corenode/utils" "0.25.0" "@corenode/utils" "0.25.1"
escape-goat "^3.0.0" escape-goat "^3.0.0"
execa "5.0.0" execa "5.0.0"
filesize "^6.3.0" filesize "^6.3.0"