1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00

Merge pull request #288 from oceanprotocol/feature/customProvider

Feature/custom provider
This commit is contained in:
Alex Coseru 2020-09-22 14:56:56 +03:00 committed by GitHub
commit e06f96af0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 121 additions and 29 deletions

View File

@ -47,4 +47,4 @@ deploy:
api_key: ${NPM_TOKEN} api_key: ${NPM_TOKEN}
skip_cleanup: true skip_cleanup: true
on: on:
tags: true tags: true

View File

@ -15,6 +15,7 @@ import { SubscribablePromise, didZeroX } from '../utils'
import { Instantiable, InstantiableConfig } from '../Instantiable.abstract' import { Instantiable, InstantiableConfig } from '../Instantiable.abstract'
import { WebServiceConnector } from './utils/WebServiceConnector' import { WebServiceConnector } from './utils/WebServiceConnector'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import { Provider } from '../provider/Provider'
import { isAddress } from 'web3-utils' import { isAddress } from 'web3-utils'
export enum CreateProgressStep { export enum CreateProgressStep {
@ -56,6 +57,7 @@ export class Assets extends Instantiable {
* @param {String} cap Maximum cap (Number) - will be converted to wei * @param {String} cap Maximum cap (Number) - will be converted to wei
* @param {String} name Token name * @param {String} name Token name
* @param {String} symbol Token symbol * @param {String} symbol Token symbol
* @param {String} providerUri
* @return {Promise<DDO>} * @return {Promise<DDO>}
*/ */
public create( public create(
@ -65,7 +67,8 @@ export class Assets extends Instantiable {
dtAddress?: string, dtAddress?: string,
cap?: string, cap?: string,
name?: string, name?: string,
symbol?: string symbol?: string,
providerUri?: string
): SubscribablePromise<CreateProgressStep, DDO> { ): SubscribablePromise<CreateProgressStep, DDO> {
if (!isAddress(dtAddress)) { if (!isAddress(dtAddress)) {
this.logger.error( this.logger.error(
@ -109,7 +112,12 @@ export class Assets extends Instantiable {
this.logger.log('Encrypting files') this.logger.log('Encrypting files')
observer.next(CreateProgressStep.EncryptingFiles) observer.next(CreateProgressStep.EncryptingFiles)
const encryptedFiles = await this.ocean.provider.encrypt( let provider
if (providerUri) {
provider = new Provider(this.instanceConfig)
provider.setBaseUrl(providerUri)
} else provider = this.ocean.provider
const encryptedFiles = await provider.encrypt(
did.getId(), did.getId(),
metadata.main.files, metadata.main.files,
publisher publisher
@ -395,12 +403,13 @@ export class Assets extends Instantiable {
creator: Account, creator: Account,
cost: string, cost: string,
datePublished: string, datePublished: string,
timeout = 0 timeout = 0,
providerUri?: string
): Promise<ServiceAccess> { ): Promise<ServiceAccess> {
return { return {
type: 'access', type: 'access',
index: 2, index: 2,
serviceEndpoint: this.ocean.provider.getConsumeEndpoint(), serviceEndpoint: providerUri || this.ocean.provider.url,
attributes: { attributes: {
main: { main: {
creator: creator.getId(), creator: creator.getId(),
@ -428,14 +437,12 @@ export class Assets extends Instantiable {
did: string, did: string,
serviceType: string, serviceType: string,
consumerAddress: string, consumerAddress: string,
serviceIndex = -1 serviceIndex = -1,
serviceEndpoint: string
): Promise<any> { ): Promise<any> {
const res = await this.ocean.provider.initialize( const provider = new Provider(this.instanceConfig)
did, provider.setBaseUrl(serviceEndpoint)
serviceIndex, const res = await provider.initialize(did, serviceIndex, serviceType, consumerAddress)
serviceType,
consumerAddress
)
if (res === null) return null if (res === null) return null
const providerData = JSON.parse(res) const providerData = JSON.parse(res)
return providerData return providerData
@ -457,11 +464,12 @@ export class Assets extends Instantiable {
serviceIndex = -1, serviceIndex = -1,
mpAddress?: string mpAddress?: string
): Promise<string> { ): Promise<string> {
let service
if (serviceIndex === -1) { if (serviceIndex === -1) {
const service = await this.getServiceByType(did, serviceType) service = await this.getServiceByType(did, serviceType)
serviceIndex = service.index serviceIndex = service.index
} else { } else {
const service = await this.getServiceByIndex(did, serviceIndex) service = await this.getServiceByIndex(did, serviceIndex)
serviceType = service.type serviceType = service.type
} }
const { datatokens } = this.ocean const { datatokens } = this.ocean
@ -470,10 +478,11 @@ export class Assets extends Instantiable {
did, did,
serviceType, serviceType,
consumerAddress, consumerAddress,
serviceIndex serviceIndex,
service.serviceEndpoint
) )
if (!providerData) return null if (!providerData) return null
const service = await this.getServiceByIndex(did, serviceIndex) service = await this.getServiceByIndex(did, serviceIndex)
const previousOrder = await datatokens.getPreviousValidOrders( const previousOrder = await datatokens.getPreviousValidOrders(
providerData.dataToken, providerData.dataToken,
providerData.numTokens, providerData.numTokens,
@ -538,8 +547,9 @@ export class Assets extends Instantiable {
destination = destination destination = destination
? `${destination}/datafile.${ddo.shortId()}.${service.index}/` ? `${destination}/datafile.${ddo.shortId()}.${service.index}/`
: undefined : undefined
const provider = new Provider(this.instanceConfig)
await this.ocean.provider.download( provider.setBaseUrl(serviceEndpoint)
await provider.download(
did, did,
txId, txId,
tokenAddress, tokenAddress,

View File

@ -6,6 +6,7 @@ import { SubscribablePromise } from '../utils'
import { Instantiable, InstantiableConfig } from '../Instantiable.abstract' import { Instantiable, InstantiableConfig } from '../Instantiable.abstract'
import { Output } from './interfaces/ComputeOutput' import { Output } from './interfaces/ComputeOutput'
import { ComputeJob } from './interfaces/ComputeJob' import { ComputeJob } from './interfaces/ComputeJob'
import { Provider } from '../provider/Provider'
export enum OrderProgressStep { export enum OrderProgressStep {
TransferDataToken TransferDataToken
@ -87,8 +88,13 @@ export class Compute extends Instantiable {
algorithmDataToken?: string algorithmDataToken?: string
): Promise<ComputeJob> { ): Promise<ComputeJob> {
output = this.checkOutput(consumerAccount, output) output = this.checkOutput(consumerAccount, output)
const ddo = await this.ocean.assets.resolve(did)
const service = ddo.findServiceByType('compute')
const { serviceEndpoint } = service
if (did && txId) { if (did && txId) {
const computeJobsList = await this.ocean.provider.compute( const provider = new Provider(this.instanceConfig)
provider.setBaseUrl(serviceEndpoint)
const computeJobsList = await provider.compute(
'post', 'post',
did, did,
consumerAccount, consumerAccount,
@ -119,7 +125,12 @@ export class Compute extends Instantiable {
did: string, did: string,
jobId: string jobId: string
): Promise<ComputeJob> { ): Promise<ComputeJob> {
const computeJobsList = await this.ocean.provider.compute( const ddo = await this.ocean.assets.resolve(did)
const service = ddo.findServiceByType('compute')
const { serviceEndpoint } = service
const provider = new Provider(this.instanceConfig)
provider.setBaseUrl(serviceEndpoint)
const computeJobsList = await provider.compute(
'put', 'put',
did, did,
consumerAccount, consumerAccount,
@ -143,7 +154,12 @@ export class Compute extends Instantiable {
did: string, did: string,
jobId: string jobId: string
): Promise<ComputeJob> { ): Promise<ComputeJob> {
const computeJobsList = await this.ocean.provider.compute( const ddo = await this.ocean.assets.resolve(did)
const service = ddo.findServiceByType('compute')
const { serviceEndpoint } = service
const provider = new Provider(this.instanceConfig)
provider.setBaseUrl(serviceEndpoint)
const computeJobsList = await provider.compute(
'delete', 'delete',
did, did,
consumerAccount, consumerAccount,
@ -167,7 +183,17 @@ export class Compute extends Instantiable {
did?: string, did?: string,
jobId?: string jobId?: string
): Promise<ComputeJob[]> { ): Promise<ComputeJob[]> {
const computeJobsList = await this.ocean.provider.compute( let provider
if (did) {
const ddo = await this.ocean.assets.resolve(did)
const service = ddo.findServiceByType('compute')
const { serviceEndpoint } = service
provider = new Provider(this.instanceConfig)
provider.setBaseUrl(serviceEndpoint)
} else {
provider = this.ocean.provider
}
const computeJobsList = await provider.compute(
'get', 'get',
did, did,
consumerAccount, consumerAccount,
@ -191,7 +217,12 @@ export class Compute extends Instantiable {
did: string, did: string,
jobId: string jobId: string
): Promise<ComputeJob> { ): Promise<ComputeJob> {
const computeJobsList = await this.ocean.provider.compute( const ddo = await this.ocean.assets.resolve(did)
const service = ddo.findServiceByType('compute')
const { serviceEndpoint } = service
const provider = new Provider(this.instanceConfig)
provider.setBaseUrl(serviceEndpoint)
const computeJobsList = await provider.compute(
'get', 'get',
did, did,
consumerAccount, consumerAccount,
@ -279,14 +310,15 @@ export class Compute extends Instantiable {
datePublished: string, datePublished: string,
providerAttributes: any, providerAttributes: any,
computePrivacy?: ServiceComputePrivacy, computePrivacy?: ServiceComputePrivacy,
timeout?: number timeout?: number,
providerUri?: string
): ServiceCompute { ): ServiceCompute {
const name = 'dataAssetComputingService' const name = 'dataAssetComputingService'
if (!timeout) timeout = 3600 if (!timeout) timeout = 3600
const service = { const service = {
type: 'compute', type: 'compute',
index: 3, index: 3,
serviceEndpoint: this.ocean.provider.getComputeEndpoint(), serviceEndpoint: providerUri || this.ocean.provider.url,
attributes: { attributes: {
main: { main: {
name, name,

View File

@ -18,16 +18,22 @@ const apiPath = '/api/v1/services'
*/ */
export class Provider extends Instantiable { export class Provider extends Instantiable {
public nonce: string public nonce: string
private get url() { private baseUrl: string
return this.config.providerUri public get url() {
return this.baseUrl
} }
constructor(config: InstantiableConfig) { constructor(config: InstantiableConfig) {
super() super()
this.setInstanceConfig(config) this.setInstanceConfig(config)
this.baseUrl = this.config.providerUri
this.nonce = '0' this.nonce = '0'
} }
public setBaseUrl(url: string): void {
this.baseUrl = url
}
public async createSignature(account: Account, agreementId: string): Promise<string> { public async createSignature(account: Account, agreementId: string): Promise<string> {
const signature = await this.ocean.utils.signature.signText( const signature = await this.ocean.utils.signature.signText(
noZeroX(agreementId), noZeroX(agreementId),
@ -264,8 +270,12 @@ export class Provider extends Instantiable {
return `${this.url}${apiPath}/nonce` return `${this.url}${apiPath}/nonce`
} }
public getConsumeEndpointPath(): string {
return `${apiPath}/consume`
}
public getConsumeEndpoint(): string { public getConsumeEndpoint(): string {
return `${this.url}${apiPath}/consume` return `${this.url}` + this.getConsumeEndpointPath()
} }
public getEncryptEndpoint(): string { public getEncryptEndpoint(): string {
@ -276,11 +286,33 @@ export class Provider extends Instantiable {
return `${this.url}${apiPath}/publish` return `${this.url}${apiPath}/publish`
} }
public getComputeEndpointPath(): string {
return `${apiPath}/compute`
}
public getComputeEndpoint(): string { public getComputeEndpoint(): string {
return `${this.url}${apiPath}/compute` return `${this.url}` + this.getComputeEndpointPath()
} }
public getDownloadEndpoint(): string { public getDownloadEndpoint(): string {
return `${this.url}${apiPath}/download` return `${this.url}${apiPath}/download`
} }
/** Check for a valid provider at URL
* @param {String} url
* @return {Promise<boolean>} string
*/
public async isValidProvider(url: string): Promise<boolean> {
try {
const response = await this.ocean.utils.fetch.get(url)
if (response?.ok) {
const params = await response.json()
if (params && params['provider-address']) return true
}
return false
} catch (error) {
this.logger.error(`Error validating provider: ${error.message}`)
return false
}
}
} }

View File

@ -0,0 +1,18 @@
import { Ocean } from '../../src/ocean/Ocean'
import config from './config'
import { assert } from 'console'
describe('Provider tests', () => {
let ocean
it('Initialize Ocean', async () => {
ocean = await Ocean.getInstance(config)
})
it('Alice tests invalid provider', async () => {
const valid = ocean.provider.isValidProvider('http://example.net')
assert(valid === false)
})
it('Alice tests valid provider', async () => {
const valid = ocean.provider.isValidProvider('http://127.0.0.1:8030')
assert(valid === true)
})
})