This commit is contained in:
boufni95 2023-12-15 20:20:03 +01:00
parent 73ec8d511d
commit b10f2b4668
13 changed files with 3274 additions and 2446 deletions

View file

@ -105,9 +105,9 @@ The nostr server will send back a message response, and inside the body there wi
- __User__:
- expected context content
- __app_user_id__: _string_
- __user_id__: _string_
- __app_id__: _string_
- __app_user_id__: _string_
- __Admin__:
- expected context content
@ -141,6 +141,13 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AuthAppRequest](#AuthAppRequest)
- output: [AuthApp](#AuthApp)
- GetMetrics
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/metrics__
- This methods has an __empty__ __request__ body
- output: [UsageMetrics](#UsageMetrics)
- Health
- auth type: __Guest__
- http method: __get__
@ -407,93 +414,42 @@ The nostr server will send back a message response, and inside the body there wi
## Messages
### The content of requests and response from the methods
### SetMockAppUserBalanceRequest
- __user_identifier__: _string_
- __amount__: _number_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### SetMockAppBalanceRequest
- __amount__: _number_
### GetAppUserLNURLInfoRequest
- __user_identifier__: _string_
- __base_url_override__: _string_
### GetAppUserRequest
- __user_identifier__: _string_
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### PayAddressRequest
- __address__: _string_
- __amoutSats__: _number_
- __satsPerVByte__: _number_
### PayInvoiceRequest
- __invoice__: _string_
- __amount__: _number_
### GetUserOperationsResponse
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
### MigrationUpdate
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
### Empty
### LndGetInfoRequest
- __nodeId__: _number_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
- __amount__: _number_
### RelaysMigration
- __relays__: ARRAY of: _string_
### LndGetInfoResponse
- __alias__: _string_
### AuthAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_ *this field is optional
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### NewAddressResponse
- __address__: _string_
### PayAddressResponse
- __txId__: _string_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### UsageMetrics
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
### AddAppUserRequest
- __identifier__: _string_
- __fail_if_exists__: _boolean_
- __balance__: _number_
### NewInvoiceResponse
- __invoice__: _string_
### OpenChannelResponse
- __channelId__: _string_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### LnurlPayInfoResponse
- __tag__: _string_
@ -504,28 +460,44 @@ The nostr server will send back a message response, and inside the body there wi
- __allowsNostr__: _boolean_
- __nostrPubkey__: _string_
### HandleLnurlPayResponse
- __pr__: _string_
- __routes__: ARRAY of: _[Empty](#Empty)_
### Product
- __id__: _string_
- __name__: _string_
- __price_sats__: _number_
### ClosureMigration
- __closes_at_unix__: _number_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### SetMockAppUserBalanceRequest
- __user_identifier__: _string_
- __amount__: _number_
### DecodeInvoiceRequest
- __invoice__: _string_
### PayInvoiceRequest
- __invoice__: _string_
- __amount__: _number_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
- __amount__: _number_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### GetAppUserRequest
- __user_identifier__: _string_
### GetAppUserLNURLInfoRequest
- __user_identifier__: _string_
- __base_url_override__: _string_
### HandleLnurlPayResponse
- __pr__: _string_
- __routes__: ARRAY of: _[Empty](#Empty)_
### UserInfo
- __userId__: _string_
- __balance__: _number_
@ -536,20 +508,48 @@ The nostr server will send back a message response, and inside the body there wi
- __toIndex__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### GetProductBuyLinkResponse
- __link__: _string_
### Product
- __id__: _string_
- __name__: _string_
- __price_sats__: _number_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### OpenChannelResponse
- __channelId__: _string_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### UsageMetric
- __processed_at_nano__: _string_
- __parsed_in_nano__: _number_
- __auth_in_nano__: _number_
- __validate_in_nano__: _number_
- __handle_in_nano__: _number_
- __rpc_name__: _string_
- __batch__: _boolean_
- __nostr__: _boolean_
- __batch_size__: _number_
### AddAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### NewInvoiceResponse
- __invoice__: _string_
### AddAppInvoiceRequest
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### LnurlWithdrawInfoResponse
- __tag__: _string_
@ -561,53 +561,6 @@ The nostr server will send back a message response, and inside the body there wi
- __balanceCheck__: _string_
- __payLink__: _string_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### AddAppInvoiceRequest
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### PayAddressResponse
- __txId__: _string_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### DecodeInvoiceResponse
- __amount__: _number_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### Application
- __name__: _string_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### OpenChannelRequest
- __destination__: _string_
- __fundingAmount__: _number_
- __pushAmount__: _number_
- __closeAddress__: _string_
### UserOperation
- __paidAtUnix__: _number_
- __type__: _[UserOperationType](#UserOperationType)_
@ -619,15 +572,83 @@ The nostr server will send back a message response, and inside the body there wi
- __network_fee__: _number_
- __confirmed__: _boolean_
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### SetMockAppBalanceRequest
- __amount__: _number_
### LiveUserOperation
- __operation__: _[UserOperation](#UserOperation)_
### RelaysMigration
- __relays__: ARRAY of: _string_
### ClosureMigration
- __closes_at_unix__: _number_
### AddAppRequest
### Empty
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### LndGetInfoRequest
- __nodeId__: _number_
### Application
- __name__: _string_
- __allow_user_creation__: _boolean_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
### GetUserOperationsResponse
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
### GetProductBuyLinkResponse
- __link__: _string_
### MigrationUpdate
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### NewAddressResponse
- __address__: _string_
### DecodeInvoiceResponse
- __amount__: _number_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
### AuthAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_ *this field is optional
### PayAddressRequest
- __address__: _string_
- __amoutSats__: _number_
- __satsPerVByte__: _number_
### OpenChannelRequest
- __destination__: _string_
- __fundingAmount__: _number_
- __pushAmount__: _number_
- __closeAddress__: _string_
## Enums
### The enumerators used in the messages

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -57,6 +57,20 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetMetrics: async (): Promise<ResultError | ({ status: 'OK' }& Types.UsageMetrics)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/admin/metrics'
const { data } = await axios.post(params.baseUrl + finalRoute, {}, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.UsageMetricsValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
Health: async (): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')

View file

@ -15,270 +15,417 @@ export type NostrRequest = {
export type NostrOptions = {
logger?: Logger
throwErrors?: true
NostrUserAuthGuard: (appId?:string, identifier?: string) => Promise<Types.UserContext>
metricsCallback: (metrics: Types.RequestMetric[]) => void
NostrUserAuthGuard: (appId?: string, identifier?: string) => Promise<Types.UserContext>
}
const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => {
logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res({ status: 'ERROR', reason: response })
}
const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger) => { logger.error(error.message || error); res({ status: 'ERROR', reason: response }) }
export default (methods: Types.ServerMethods, opts: NostrOptions) => {
const logger = opts.logger || { log: console.log, error: console.error }
return async (req: NostrRequest, res: NostrResponse) => {
return async (req: NostrRequest, res: NostrResponse, startTime: bigint) => {
const info: Types.RequestInfo = { rpcName: req.rpcName || 'unkown', batch: false, nostr: true, batchSize: 0 }
const stats: Types.RequestStats = { start: startTime, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
let authCtx: Types.AuthContext = {}
switch (req.rpcName) {
case 'GetUserInfo':
try {
if (!methods.GetUserInfo) throw new Error('method: GetUserInfo is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const response = await methods.GetUserInfo({rpcName:'GetUserInfo', ctx:authContext })
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.GetUserInfo({ rpcName: 'GetUserInfo', ctx: authContext })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'AddProduct':
try {
if (!methods.AddProduct) throw new Error('method: AddProduct is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.AddProductRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.AddProduct({rpcName:'AddProduct', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.AddProduct({ rpcName: 'AddProduct', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'NewProductInvoice':
try {
if (!methods.NewProductInvoice) throw new Error('method: NewProductInvoice is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const response = await methods.NewProductInvoice({rpcName:'NewProductInvoice', ctx:authContext ,query: req.query||{}})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.NewProductInvoice({ rpcName: 'NewProductInvoice', ctx: authContext, query: req.query || {} })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetUserOperations':
try {
if (!methods.GetUserOperations) throw new Error('method: GetUserOperations is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.GetUserOperationsRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.GetUserOperations({rpcName:'GetUserOperations', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.GetUserOperations({ rpcName: 'GetUserOperations', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'NewAddress':
try {
if (!methods.NewAddress) throw new Error('method: NewAddress is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.NewAddressRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.NewAddress({rpcName:'NewAddress', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.NewAddress({ rpcName: 'NewAddress', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'PayAddress':
try {
if (!methods.PayAddress) throw new Error('method: PayAddress is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.PayAddressRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.PayAddress({rpcName:'PayAddress', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.PayAddress({ rpcName: 'PayAddress', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'NewInvoice':
try {
if (!methods.NewInvoice) throw new Error('method: NewInvoice is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.NewInvoiceRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.NewInvoice({rpcName:'NewInvoice', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.NewInvoice({ rpcName: 'NewInvoice', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'DecodeInvoice':
try {
if (!methods.DecodeInvoice) throw new Error('method: DecodeInvoice is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.DecodeInvoiceRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.DecodeInvoice({rpcName:'DecodeInvoice', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.DecodeInvoice({ rpcName: 'DecodeInvoice', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'PayInvoice':
try {
if (!methods.PayInvoice) throw new Error('method: PayInvoice is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.PayInvoiceRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.PayInvoice({rpcName:'PayInvoice', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.PayInvoice({ rpcName: 'PayInvoice', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'OpenChannel':
try {
if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.OpenChannelRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const response = await methods.OpenChannel({rpcName:'OpenChannel', ctx:authContext , req: request})
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.OpenChannel({ rpcName: 'OpenChannel', ctx: authContext, req: request })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetLnurlWithdrawLink':
try {
if (!methods.GetLnurlWithdrawLink) throw new Error('method: GetLnurlWithdrawLink is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const response = await methods.GetLnurlWithdrawLink({rpcName:'GetLnurlWithdrawLink', ctx:authContext })
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.GetLnurlWithdrawLink({ rpcName: 'GetLnurlWithdrawLink', ctx: authContext })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetLnurlPayLink':
try {
if (!methods.GetLnurlPayLink) throw new Error('method: GetLnurlPayLink is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const response = await methods.GetLnurlPayLink({rpcName:'GetLnurlPayLink', ctx:authContext })
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.GetLnurlPayLink({ rpcName: 'GetLnurlPayLink', ctx: authContext })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetLNURLChannelLink':
try {
if (!methods.GetLNURLChannelLink) throw new Error('method: GetLNURLChannelLink is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const response = await methods.GetLNURLChannelLink({rpcName:'GetLNURLChannelLink', ctx:authContext })
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.GetLNURLChannelLink({ rpcName: 'GetLNURLChannelLink', ctx: authContext })
stats.handle = process.hrtime.bigint()
res({ status: 'OK', ...response })
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetLiveUserOperations':
try {
if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
methods.GetLiveUserOperations({rpcName:'GetLiveUserOperations', ctx:authContext ,cb: (response, err) => {
if (err) { logErrorAndReturnResponse(err, err.message, res, logger)} else { res({status: 'OK', ...response})}
}})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
methods.GetLiveUserOperations({
rpcName: 'GetLiveUserOperations', ctx: authContext, cb: (response, err) => {
stats.handle = process.hrtime.bigint()
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) } else { res({ status: 'OK', ...response }); opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }
}
})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'GetMigrationUpdate':
try {
if (!methods.GetMigrationUpdate) throw new Error('method: GetMigrationUpdate is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
methods.GetMigrationUpdate({rpcName:'GetMigrationUpdate', ctx:authContext ,cb: (response, err) => {
if (err) { logErrorAndReturnResponse(err, err.message, res, logger)} else { res({status: 'OK', ...response})}
}})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
methods.GetMigrationUpdate({
rpcName: 'GetMigrationUpdate', ctx: authContext, cb: (response, err) => {
stats.handle = process.hrtime.bigint()
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) } else { res({ status: 'OK', ...response }); opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }
}
})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'BatchUser':
try {
info.batch = true
const requests = req.body.requests as Types.UserMethodInputs[]
if (!Array.isArray(requests))throw new Error('invalid body, is not an array')
if (!Array.isArray(requests)) throw new Error('invalid body, is not an array')
info.batchSize = requests.length
if (requests.length > 10) throw new Error('too many requests in the batch')
const ctx = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = ctx
stats.validate = stats.guard
const responses = []
const callsMetrics: Types.RequestMetric[] = []
for (let i = 0; i < requests.length; i++) {
const operation = requests[i]
const opInfo: Types.RequestInfo = { rpcName: operation.rpcName, batch: true, nostr: true, batchSize: 0 }
const opStats: Types.RequestStats = { start: startTime, parse: stats.parse, guard: stats.guard, validate: 0n, handle: 0n }
try {
switch(operation.rpcName) {
switch (operation.rpcName) {
case 'GetUserInfo':
if (!methods.GetUserInfo) {
responses.push({ status: 'ERROR', reason: 'method not defined: GetUserInfo' })
throw new Error('method not defined: GetUserInfo')
} else {
const res = await methods.GetUserInfo({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.validate = opStats.guard
const res = await methods.GetUserInfo({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'AddProduct':
if (!methods.AddProduct) {
responses.push({ status: 'ERROR', reason: 'method not defined: AddProduct' })
throw new Error('method not defined: AddProduct')
} else {
const res = await methods.AddProduct({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.AddProductRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.AddProduct({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'NewProductInvoice':
if (!methods.NewProductInvoice) {
responses.push({ status: 'ERROR', reason: 'method not defined: NewProductInvoice' })
throw new Error('method not defined: NewProductInvoice')
} else {
const res = await methods.NewProductInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.validate = opStats.guard
const res = await methods.NewProductInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetUserOperations':
if (!methods.GetUserOperations) {
responses.push({ status: 'ERROR', reason: 'method not defined: GetUserOperations' })
throw new Error('method not defined: GetUserOperations')
} else {
const res = await methods.GetUserOperations({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.GetUserOperationsRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.GetUserOperations({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'NewAddress':
if (!methods.NewAddress) {
responses.push({ status: 'ERROR', reason: 'method not defined: NewAddress' })
throw new Error('method not defined: NewAddress')
} else {
const res = await methods.NewAddress({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.NewAddressRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.NewAddress({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'PayAddress':
if (!methods.PayAddress) {
responses.push({ status: 'ERROR', reason: 'method not defined: PayAddress' })
throw new Error('method not defined: PayAddress')
} else {
const res = await methods.PayAddress({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.PayAddressRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.PayAddress({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'NewInvoice':
if (!methods.NewInvoice) {
responses.push({ status: 'ERROR', reason: 'method not defined: NewInvoice' })
throw new Error('method not defined: NewInvoice')
} else {
const res = await methods.NewInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.NewInvoiceRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.NewInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'DecodeInvoice':
if (!methods.DecodeInvoice) {
responses.push({ status: 'ERROR', reason: 'method not defined: DecodeInvoice' })
throw new Error('method not defined: DecodeInvoice')
} else {
const res = await methods.DecodeInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.DecodeInvoiceRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.DecodeInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'PayInvoice':
if (!methods.PayInvoice) {
responses.push({ status: 'ERROR', reason: 'method not defined: PayInvoice' })
throw new Error('method not defined: PayInvoice')
} else {
const res = await methods.PayInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.PayInvoiceRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.PayInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'OpenChannel':
if (!methods.OpenChannel) {
responses.push({ status: 'ERROR', reason: 'method not defined: OpenChannel' })
throw new Error('method not defined: OpenChannel')
} else {
const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res })
const error = Types.OpenChannelRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.OpenChannel({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetLnurlWithdrawLink':
if (!methods.GetLnurlWithdrawLink) {
responses.push({ status: 'ERROR', reason: 'method not defined: GetLnurlWithdrawLink' })
throw new Error('method not defined: GetLnurlWithdrawLink')
} else {
const res = await methods.GetLnurlWithdrawLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.validate = opStats.guard
const res = await methods.GetLnurlWithdrawLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetLnurlPayLink':
if (!methods.GetLnurlPayLink) {
responses.push({ status: 'ERROR', reason: 'method not defined: GetLnurlPayLink' })
throw new Error('method not defined: GetLnurlPayLink')
} else {
const res = await methods.GetLnurlPayLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.validate = opStats.guard
const res = await methods.GetLnurlPayLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetLNURLChannelLink':
if (!methods.GetLNURLChannelLink) {
responses.push({ status: 'ERROR', reason: 'method not defined: GetLNURLChannelLink' })
throw new Error('method not defined: GetLNURLChannelLink')
} else {
const res = await methods.GetLNURLChannelLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.validate = opStats.guard
const res = await methods.GetLNURLChannelLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
default:
throw new Error('unkown rpcName')
}
} catch(ex) {const e = ex as any; logger.error(e.message || e); responses.push({ status: 'ERROR', reason: e.message || e })}
} catch (ex) { const e = ex as any; logger.error(e.message || e); callsMetrics.push({ ...opInfo, ...opStats, ...ctx, error: e.message }); responses.push({ status: 'ERROR', reason: e.message || e }) }
}
res({ status: 'OK', responses })
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
default: logger.error('unknown rpc call name from nostr event:'+req.rpcName)
default: logger.error('unknown rpc call name from nostr event:' + req.rpcName)
}
}
}

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -96,6 +96,12 @@ service LightningPub {
option (http_method) = "post";
option (http_route) = "/api/admin/app/auth";
}
rpc GetMetrics(structs.Empty) returns (structs.UsageMetrics) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/metrics";
}
// </Admin>
// <Guest>

View file

@ -12,6 +12,22 @@ message EncryptionExchangeRequest {
string deviceId = 2;
}
message UsageMetric {
string processed_at_nano = 1;
int64 parsed_in_nano = 2;
int64 auth_in_nano = 3;
int64 validate_in_nano = 4;
int64 handle_in_nano = 5;
string rpc_name = 6;
bool batch = 7;
bool nostr = 8;
int64 batch_size = 9;
}
message UsageMetrics {
repeated UsageMetric metrics = 1;
}
message LndGetInfoRequest {
int64 nodeId = 1;
}

View file

@ -10,6 +10,7 @@ const serverOptions = (mainHandler: Main): ServerOptions => {
AppAuthGuard: async (authHeader) => { return { app_id: mainHandler.applicationManager.DecodeAppToken(stripBearer(authHeader)) } },
UserAuthGuard: async (authHeader) => { return mainHandler.appUserManager.DecodeUserToken(stripBearer(authHeader)) },
GuestAuthGuard: async (_) => ({}),
metricsCallback: metrics => mainHandler.metricsManager.AddMetrics(metrics)
//throwErrors: true
}
}

View file

@ -15,6 +15,7 @@ import { Application } from '../storage/entity/Application.js'
import { UserReceivingInvoice, ZapInfo } from '../storage/entity/UserReceivingInvoice.js'
import { UnsignedEvent } from '../nostr/tools/event.js'
import { NostrSend } from '../nostr/handler.js'
import MetricsManager from '../metrics/index.js'
export const LoadMainSettingsFromEnv = (test = false): MainSettings => {
return {
lndSettings: LoadLndSettingsFromEnv(test),
@ -51,11 +52,13 @@ export default class {
appUserManager: AppUserManager
paymentManager: PaymentManager
paymentSubs: Record<string, ((op: Types.UserOperation) => void) | null> = {}
metricsManager: MetricsManager
nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") }
constructor(settings: MainSettings) {
this.settings = settings
this.storage = new Storage(settings.storageSettings)
this.metricsManager = new MetricsManager()
this.lnd = NewLightningHandler(settings.lndSettings, this.addressPaidCb, this.invoicePaidCb, this.newBlockCb)
this.paymentManager = new PaymentManager(this.storage, this.lnd, this.settings, this.addressPaidCb, this.invoicePaidCb)

View file

@ -0,0 +1,27 @@
import * as Types from '../../../proto/autogenerated/ts/types'
const maxEvents = 100_000
export default class Handler {
metrics: Types.UsageMetric[] = []
AddMetrics(newMetrics: Types.RequestMetric[]) {
const parsed: Types.UsageMetric[] = newMetrics.map(m => ({
rpc_name: m.rpcName,
processed_at_nano: m.start.toString(),
batch: m.batch,
nostr: m.nostr,
batch_size: m.batchSize,
parsed_in_nano: Number(m.parse - m.start),
auth_in_nano: Number(m.guard - m.parse),
validate_in_nano: Number(m.validate - m.guard),
handle_in_nano: Number(m.handle - m.validate)
}))
const len = this.metrics.push(...parsed)
if (len > maxEvents) {
this.metrics.splice(0, len - maxEvents)
}
}
async GetMetrics(): Promise<Types.UsageMetrics> {
return {
metrics: this.metrics
}
}
}

View file

@ -1,8 +1,12 @@
import * as Types from '../../../proto/autogenerated/ts/types.js'
import { getLogger } from '../helpers/logger.js'
import main from '../main/index.js'
import Main from '../main/index.js'
export default (mainHandler: Main): Types.ServerMethods => {
return {
GetMetrics: async ({ ctx }) => {
return mainHandler.metricsManager.GetMetrics()
},
EncryptionExchange: async () => { },
Health: async () => { await mainHandler.lnd.Health() },
LndGetInfo: async ({ ctx }) => {