Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/db/models/all/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1374,7 +1374,7 @@ export const updateDevicesOriginGroup = async(serial, group) => {
db.devices.updateOne({serial}, update)
)

if (stats.modifiedCount) {
if (stats.modifiedCount || stats.matchedCount) {
log.info(
'[updateDevicesOriginGroup] Successfully updated origin group in device [serial: "%s", group: "%s", name: "%s"]',
serial,
Expand Down
56 changes: 0 additions & 56 deletions lib/db/proxiedModel.js

This file was deleted.

38 changes: 38 additions & 0 deletions lib/db/proxiedModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import * as Sentry from '@sentry/node'

// ----------------------------------Proxy all methods for Sentry error tracing---------------------------------------//

const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg
const ARGUMENT_NAMES = /([^\s,]+)/g

// TODO: argument names can be simplified after build
function getArgumentsNames(fn: Function) {
const fnStr = fn.toString().replace(STRIP_COMMENTS, '')
let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES)
return result || []
}

const getAddedAttributes = (fn: Function, args: any[]) => Object.fromEntries(
getArgumentsNames(fn).map((argument, i) => [
`dbapi.${argument}`,
args[i]
])
)

export default <T extends Record<string, any>>(model: T) => Object.keys(model).reduce((proxiedModel, method) => {
if (typeof model[method] !== 'function') {
proxiedModel[method] = model[method]
return proxiedModel
}

proxiedModel[method] = (...args: any[]) => Sentry.startSpan(
{
op: 'dbapi',
name: method,
attributes: getAddedAttributes(model[method], args)
}
, () => model[method](...args)
)
return proxiedModel
}, {} as any) as T

22 changes: 11 additions & 11 deletions lib/units/api/controllers/devices.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import useDevice, {UseDeviceError} from '../helpers/useDevice.js'
import * as Sentry from '@sentry/node'
import {accessTokenAuth} from '../helpers/securityHandlers.js'
import {DeviceOriginGroupMessage} from '../../../wire/wire.js'
var log = logger.createLogger('api:controllers:devices')
const log = logger.createLogger('api:controllers:devices')

/* ------------------------------------ PRIVATE FUNCTIONS ------------------------------- */
function filterGenericDevices(req, res, devices) {
Expand Down Expand Up @@ -237,8 +237,8 @@ function getDevices(req, res) {
}
}
function getDeviceBySerial(req, res) {
var serial = req.params.serial
var fields = req.query.fields
const serial = req.params.serial
const fields = req.query.fields
dbapi.loadDevice(req.user.groups.subscribed, serial)
.then(device => {
if (!device) {
Expand All @@ -263,8 +263,8 @@ function getDeviceBySerial(req, res) {
})
}
function getDeviceSize(req, res) {
var serial = req.params.serial
dbapi.getDeviceDisplaySize(serial)
const serial = req.params.serial
return dbapi.getDeviceDisplaySize(serial)
.then(response => {
return res.status(200).json(response.display)
})
Expand Down Expand Up @@ -295,8 +295,8 @@ function getDeviceGroups(req, res) {
})
}
function getDeviceOwner(req, res) {
var serial = req.params.serial
dbapi.getDeviceGroupOwner(serial)
const serial = req.params.serial
return dbapi.getDeviceGroupOwner(serial)
.then(response => {
if (!response) {
return res.status(404).json({
Expand All @@ -312,8 +312,8 @@ function getDeviceOwner(req, res) {
})
}
function getDeviceType(req, res) {
var serial = req.params.serial
dbapi.getDeviceType(serial)
const serial = req.params.serial
return dbapi.getDeviceType(serial)
.then(response => {
return res.status(200).json(response)
})
Expand Down Expand Up @@ -481,12 +481,12 @@ function removeOriginGroupDevice(req, res) {
function putDeviceInfoBySerial(req, res) {
const serial = req.params.serial
const body = req.body
dbapi.loadDeviceBySerial(serial)
return dbapi.loadDeviceBySerial(serial)
.then((data) => {
if (!data) {
return apiutil.respond(res, 404, `Not Found (${serial})`)
}
var updates = []
const updates = []
// Update fields based on given body
if (_.has(body, 'note')) {
updates.push(dbapi.setDeviceNote(serial, body.note))
Expand Down
33 changes: 19 additions & 14 deletions lib/units/api/controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function getUser(req, res) {
}

function getUserDevices(req, res) {
var fields = req.query.fields
const fields = req.query.fields
log.info('Loading user devices')
dbapi.loadUserDevices(req.user.email)
.then(list => {
Expand Down Expand Up @@ -78,9 +78,9 @@ function getUserDevices(req, res) {
}

function getUserDeviceBySerial(req, res) {
var serial = req.params.serial
var fields = req.query.fields
dbapi.loadDevice(req.user.groups.subscribed, serial)
const serial = req.params.serial
const fields = req.query.fields
return dbapi.loadDevice(req.user.groups.subscribed, serial)
.then(function(device) {
if (!device) {
return res.status(404).json({
Expand All @@ -95,7 +95,7 @@ function getUserDeviceBySerial(req, res) {
description: 'Device is not owned by you'
})
}
var responseDevice = device
let responseDevice = device
if (fields) {
responseDevice = _.pick(device, fields.split(','))
}
Expand All @@ -116,7 +116,7 @@ function addUserDevice(req, res) {
let timeout = Object.prototype.hasOwnProperty.call(req, 'body') ? req.body.timeout ||
null : req.query.timeout || null
const lock = {}
lockutil.lockGenericDevice(req, res, lock, dbapi.lockDeviceByCurrent)
return lockutil.lockGenericDevice(req, res, lock, dbapi.lockDeviceByCurrent)
.then(function(lockingSuccessed) {
if (lockingSuccessed) {
const device = lock.device
Expand Down Expand Up @@ -183,7 +183,7 @@ function deleteUserDeviceBySerial(req, res) {
else {
serial = req.params.serial
}
dbapi.loadDevice(req.user.groups.subscribed, serial)
return dbapi.loadDevice(req.user.groups.subscribed, serial)
.then(async function(device) {
if (!device) {
if (isInternal) {
Expand Down Expand Up @@ -216,13 +216,18 @@ function deleteUserDeviceBySerial(req, res) {
}
}

await runTransaction(device.channel, UngroupMessage.create({
await runTransaction(device.channel, UngroupMessage, {
requirements: wireutil.toDeviceRequirements({
serial: {
value: serial,
match: 'exact'
}
})}))
})
}, {
sub: req.options.sub,
push: req.options.push,
channelRouter: req.options.channelRouter
})
})
.catch(function(err) {
let errSerial
Expand All @@ -244,7 +249,7 @@ function deleteUserDeviceBySerial(req, res) {

function remoteConnectUserDeviceBySerial(req, res) {
let serial = req.params.serial
dbapi.loadDevice(req.user.groups.subscribed, serial)
return dbapi.loadDevice(req.user.groups.subscribed, serial)
.then(function(device) {
if (!device) {
return res.status(404).json({
Expand Down Expand Up @@ -302,7 +307,7 @@ function remoteDisconnectUserDeviceBySerial(req, res) {
else {
serial = req.params.serial
}
dbapi.loadDevice(req.user.groups.subscribed, serial)
return dbapi.loadDevice(req.user.groups.subscribed, serial)
.then(function(device) {
if (!device) {
if (isInternal) {
Expand All @@ -327,10 +332,10 @@ function remoteDisconnectUserDeviceBySerial(req, res) {
})
}
}
var responseChannel = 'txn_' + uuidv4()
const responseChannel = 'txn_' + uuidv4()
req.options.sub.subscribe(responseChannel)
// Timer will be called if no JoinGroupMessage is received till 5 seconds
var timer = setTimeoutS(function() {
const timer = setTimeoutS(function() {
req.options.channelRouter.removeListener(responseChannel, messageListener)
req.options.sub.unsubscribe(responseChannel)
if (isInternal) {
Expand All @@ -340,7 +345,7 @@ function remoteDisconnectUserDeviceBySerial(req, res) {
return apiutil.respond(res, 504, 'Device is not responding')
}
}, apiutil.GRPC_WAIT_TIMEOUT)
var messageListener = new WireRouter()
const messageListener = new WireRouter()
.on(ConnectStoppedMessage, function(channel, message) {
if (message.serial === serial) {
clearTimeout(timer)
Expand Down
35 changes: 24 additions & 11 deletions lib/units/api/helpers/useDevice.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import wire from '../../../wire/index.js'
import {v4 as uuidv4} from 'uuid'
import {Log} from '../../../util/logger.js'
import {runTransaction} from '../../../wire/transmanager.js'
import {ConnectStartedMessage, JoinGroupMessage} from '../../../wire/wire.js'
import {ConnectStartedMessage, GroupMessage, JoinGroupMessage, OwnerMessage, UngroupMessage} from '../../../wire/wire.js'

export const UseDeviceError = Object.freeze({
NOT_FOUND: 0,
Expand Down Expand Up @@ -50,10 +50,12 @@ const useDevice = ({user, device, channelRouter, push, sub, usage = null, log})
})

try {
await runTransaction(device.channel, new wire.UngroupMessage(deviceRequirements), {sub, push, channelRouter})
await runTransaction(device.channel, UngroupMessage, {
requirements: deviceRequirements
}, {sub, push, channelRouter})
}
catch (/** @type {any} */e) {
log?.info('Transaction failed: $s', e?.message)
log?.info('Transaction failed: %s', e?.message)
}

const responseTimeout = setTimeout(function() {
Expand All @@ -73,7 +75,7 @@ const useDevice = ({user, device, channelRouter, push, sub, usage = null, log})
sub.subscribe(responseChannel)

const connectTimeout = setTimeout(function() {
channelRouter.removeListener(responseChannel, useDeviceMessageListener)
channelRouter.removeListener(responseChannel, messageListener)
sub.unsubscribe(responseChannel)

reject(UseDeviceError.FAILED_CONNECT)
Expand Down Expand Up @@ -102,13 +104,24 @@ const useDevice = ({user, device, channelRouter, push, sub, usage = null, log})

channelRouter.on(wireutil.global, useDeviceMessageListener)

await runTransaction(device.channel, new wire.GroupMessage(
new wire.OwnerMessage(user.email, user.name, user.group)
, timeout
, deviceRequirements
, usage
, user.adbKeys.map((/** @type {{ fingerprint: string }} */ k) => k.fingerprint)
), {sub, push, channelRouter})
try {
await runTransaction(device.channel, GroupMessage, {
owner: OwnerMessage.create({
email: user.email,
name: user.name,
group: user.group
}),
requirements: deviceRequirements,
usage: usage || undefined,
keys: user.adbKeys?.map((/** @type {{ fingerprint: string }} */ k) => k.fingerprint) || []
}, {sub, push, channelRouter})
}
catch (/** @type {any} */e) {
log?.info('Transaction failed: %s', e?.message)
clearTimeout(responseTimeout)
channelRouter.removeListener(wireutil.global, useDeviceMessageListener)
return reject(UseDeviceError.FAILED_JOIN)
}
})

export default useDevice
2 changes: 1 addition & 1 deletion lib/units/poorxy/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default (function(options) {
let server = http.createServer(app)
let proxy = httpProxy.createProxyServer()
proxy.on('error', function(err) {
log.error('Proxy had an error', err.stack)
log.error('Proxy had an error %s', err?.message)
})
app.use(function(req, res, next) {
res.setHeader('X-devicehub-unit', 'poorxy')
Expand Down
Loading