Git Product home page Git Product logo

nodejs-sdk's Introduction

Yandex.Cloud SDK (nodejs)

npm License

Need to automate your infrastructure or use services provided by Yandex.Cloud? We've got you covered.

Requirements

  • nodejs >= 12

Installation

npm install @yandex-cloud/nodejs-sdk

Getting started

There are three options for authorization your requests:

OAuth Token

import { Session, cloudApi, serviceClients } from '@yandex-cloud/nodejs-sdk';

const { resourcemanager: { cloud_service: { ListCloudsRequest } } } = cloudApi;

// Initialize SDK with your token
const session = new Session({ oauthToken: 'YOUR_TOKEN' });

// Create service client
const cloudService = session.client(serviceClients.CloudServiceClient);

// Issue request (returns Promise)
const response = await cloudService.list(ListCloudsRequest.fromPartial({
    pageSize: 100,
}));

Metadata Service

Don't forget to assign Service Account for your Instance or Function.

import { Session, cloudApi, serviceClients } from '@yandex-cloud/nodejs-sdk';

const { resourcemanager: { cloud_service: { ListCloudsRequest } } } = cloudApi;

// Initialize SDK with your token
const session = new Session();

// Create service client
const cloudService = session.client(serviceClients.CloudServiceClient);

// Issue request (returns Promise)
const response = await cloudService.list(ListCloudsRequest.fromPartial({
    pageSize: 100,
}));

IAM Token

import { Session, cloudApi, serviceClients } from '@yandex-cloud/nodejs-sdk';

const { resourcemanager: { cloud_service: { ListCloudsRequest } } } = cloudApi;

// Initialize SDK with your token
const session = new Session({ iamToken: 'YOUR_TOKEN' });

// Create service client
const cloudService = session.client(serviceClients.CloudServiceClient);

// Issue request (returns Promise)
const response = await cloudService.list(ListCloudsRequest.fromPartial({
    pageSize: 100,
}));

Check examples directory for more examples.

To run example scripts, you should execute the following commands:

cd examples
npm i
YC_OAUTH_TOKEN=... YC_FOLDER_ID=... npm run start path/to/example.ts

Services

  • AI Translate;
  • AI Vision.
  • Application Load Balancer
  • Billing
  • Cloud CDN
  • Certificate Manager
  • Compute Cloud
  • Container Registry
  • Data Proc
  • DataSphere
  • Data Transfer
  • DNS
  • Identity and Access Management (IAM)
  • IoT Core
  • Managed Service for Kubernetes
  • Key Management Service (KMS)
  • Load Balancer
  • Lockbox
  • Logging
  • Managed DataBase
    • ClickHouse
    • ElasticSearch
    • Greenplum
    • Kafka
    • MongoDB
    • MySQL
    • PostgreSQL
    • Redis
    • MS SQL Server
  • Organization Manager
  • Resource Manager
  • Serverless
    • Functions
    • API Gateway
    • Containers
    • Triggers
    • MDB Proxy
  • Virtual Private Cloud (VPC)
  • Yandex Database (YDB)

If you need generated client for other Yandex.Cloud services, just open an issue.

nodejs-sdk's People

Contributors

davyjohnes avatar dependabot[bot] avatar gespispace avatar nikolaymatrosov avatar vermilion avatar yandex-cloud-bot avatar ydbdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

nodejs-sdk's Issues

Add API Gateway client

As it said in the README «If you need generated client for other Yandex.Cloud services, just open an issue».
If it possible I would like to get clients for all available services, please.

GRPC API не отвечает по IPv6, из-за этого процесс завершается очень долго

Привет! Заметил, что все мои скрипты использующие sdk стали перед выходом зависать на 5 - 10 секунд.
Дебаг показал, что проблема в следующем.
DNS эндпойнты yandex-cloud резолвится в 2 айпишника: IPv4 и IPv6.
Далее grpc-js пытается приконнектиться к обоим айпишникам. С IPv4 все ок, а IPv6 остается в статусе CONNECTING.
После того, как все операции выполнены через IPv4, завершение http2 сессии с IPv6 и занимает такое долгое время.
По крайней мере на моей локальной машине (osx, nodejs 16).

Для демонстрации можно взять код из readme:

import { Session, cloudApi, serviceClients } from '@yandex-cloud/nodejs-sdk';
const { resourcemanager: { cloud_service: { ListCloudsRequest } } } = cloudApi;

const iamToken = '...';

main();

async function main() {
  const session = new Session({ iamToken });
  const cloudService = session.client(serviceClients.CloudServiceClient);
  const response = await cloudService.list(ListCloudsRequest.fromPartial({ pageSize: 10 }));
  console.log(response);
}

Запускаем с дебагом grpc:

GRPC_TRACE=subchannel,dns_resolver GRPC_VERBOSITY=DEBUG node grpc.mjs

Видно, что коннект к 84.201.181.26 успешно прошел, а к 2a0d:d6c1:0:1c::4e:

D 2022-02-14T11:37:15.152Z | dns_resolver | Resolver constructed for target dns:resource-manager.api.cloud.yandex.net:443
D 2022-02-14T11:37:15.157Z | dns_resolver | Resolution update requested for target dns:resource-manager.api.cloud.yandex.net:443
D 2022-02-14T11:37:15.162Z | dns_resolver | Resolved addresses for target dns:resource-manager.api.cloud.yandex.net:443: [2a0d:d6c1:0:1c::4e:443,84.201.181.26:443]
D 2022-02-14T11:37:15.163Z | subchannel | (2) 2a0d:d6c1:0:1c::4e:443 Subchannel constructed with options {}
D 2022-02-14T11:37:15.164Z | subchannel | (3) 84.201.181.26:443 Subchannel constructed with options {}
D 2022-02-14T11:37:15.165Z | subchannel | (2) 2a0d:d6c1:0:1c::4e:443 IDLE -> CONNECTING
D 2022-02-14T11:37:15.166Z | subchannel | (3) 84.201.181.26:443 IDLE -> CONNECTING
D 2022-02-14T11:37:15.166Z | subchannel | (2) 2a0d:d6c1:0:1c::4e:443 creating HTTP/2 session
D 2022-02-14T11:37:15.170Z | subchannel | (3) 84.201.181.26:443 creating HTTP/2 session
D 2022-02-14T11:37:15.287Z | subchannel | (3) 84.201.181.26:443 CONNECTING -> READY
{
  '$type': 'yandex.cloud.resourcemanager.v1.ListCloudsResponse',
  nextPageToken: '',
  clouds: []
}
D 2022-02-14T11:37:25.171Z | subchannel | (2) 2a0d:d6c1:0:1c::4e:443 CONNECTING -> TRANSIENT_FAILURE
D 2022-02-14T11:37:25.179Z | subchannel | (2) 2a0d:d6c1:0:1c::4e:443 TRANSIENT_FAILURE -> IDLE

У меня этот скрипт зависает секунд на 10 и только потом выходит.
Если закомментить получение IPv6 в grpc-js, то скрипт выходит моментально.

Не уверен, что это вопрос именно к SDK, но все же какие варианты убрать эти задержки?
Или на стороне сервера сделать чтобы эндпойнты отвечали по IPv6?
А то очень некомфортно работать с этими зависаниями(

Error: PayloadService/Get UNIMPLEMENTED

Hey guys,
First of all - thank you for this helpful library.

I try to retrieve secrets from LockBox and use this code:

import { Session, cloudApi, serviceClients } from '@yandex-cloud/nodejs-sdk';
const { lockbox: { payload_service: { GetPayloadRequest } }} = cloudApi;

const session = new Session({ oauthToken: '***' });
const cloudService = session.client(serviceClients.PayloadServiceClient);

const res = await cloudService.get(GetPayloadRequest.fromPartial({ secretId: 'e6qesqf9jg***'}))
console.log(res);

but get the error:

/tmp/node_modules/nice-grpc/src/client/wrapClientError.ts:7
    return new ClientError(path, error.code, error.details);
           ^
ClientError: /yandex.cloud.lockbox.v1.PayloadService/Get UNIMPLEMENTED: 

What did I do wrong?

My environment:

Node: v17.8.0
@yandex-cloud/[email protected]
macOS: 12.2.1

TypeError: Cannot destructure property 'idempotencyLevel' of 'call.method.options' as it is undefined.

В релизе 2.4.0 появилась ошибка

TypeError: Cannot destructure property 'idempotencyLevel' of 'call.method.options' as it is undefined.
    at retryMiddleware (C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\node_modules\nice-grpc-client-middleware-retry\lib\index.js:21:13)
    at retryMiddleware.next (<anonymous>)
    at deadlineMiddleware (C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\node_modules\nice-grpc-client-middleware-deadline\lib\index.js:11:28)
    at deadlineMiddleware.next (<anonymous>)
    at Object.list (C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\node_modules\nice-grpc\lib\client\createUnaryMethod.js:63:37)
    at C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\dist\index.js:83:35
    at Generator.next (<anonymous>)
    at C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\dist\index.js:31:71
    at new Promise (<anonymous>)
    at __awaiter (C:\Users\Artem\Documents\NodeJS\projects\delivery-bot\dist\index.js:27:12)

Вероятно из-за добавления новой библиотеки nice-grpc-client-middleware-retry

Error: yandex.cloud.iot.broker.v1.BrokerDataService/Publish UNIMPLEMENTED

Проблема при отправке сообщения в топик.

import { cloudApi, serviceClients, Session } from '@yandex-cloud/nodejs-sdk'
import { getEnv } from './getEnv'
import { logger } from './logger'

const session = new Session({ iamToken: getEnv('TEMP_YC_TOKEN') })

const iotService = session.client(serviceClients.BrokerDataServiceClient)

const DB_CLUSTER_ID = getEnv('DB_CLUSTER_ID')

const brokerId = getEnv('TRIGGERS_BROKER_ID')
const topic = getEnv('DB_ENTITY_CREATED_TOPIC_NAME')

export const publishMessage = async (subdomain) => {
  try {
    const req = cloudApi.iot.broker_broker_data_service.PublishBrokerDataRequest.fromJSON({
      brokerId,
      topic,
      data: subdomain,
    })
    await iotService.publish(req)
    logger.info('Message published for $s', subdomain)
  } catch (error) {
    logger.error(error.message, error)
  }
}

Error:

{
  code: 12,
  details: '',
  level: 'error',
  message:
    '/yandex.cloud.iot.broker.v1.BrokerDataService/Publish UNIMPLEMENTED:  /yandex.cloud.iot.broker.v1.BrokerDataService/Publish UNIMPLEMENTED: ',
  path: '/yandex.cloud.iot.broker.v1.BrokerDataService/Publish',
  stack:
    'ClientError: /yandex.cloud.iot.broker.v1.BrokerDataService/Publish UNIMPLEMENTED: 
    at wrapClientError (D:\\project\\node_modules\\nice-grpc\\src\\client\\wrapClientError.ts:7:12)
    at Object.callback (D:\\project\\node_modules\\nice-grpc\\src\\client\\createUnaryMethod.ts:64:35)
    at Object.onReceiveStatus (D:\\project\\node_modules\\@grpc\\grpc-js\\src\\client.ts:356:26)
    at Object.onReceiveStatus (D:\\project\\node_modules\\@grpc\\grpc-js\\src\\client-interceptors.ts:455:34)
    at Object.onReceiveStatus (D:\\project\\node_modules\\@grpc\\grpc-js\\src\\client-interceptors.ts:417:48)
    at D:\\project\\node_modules\\@grpc\\grpc-js\\src\\resolving-call.ts:111:24
    at processTicksAndRejections (node:internal/process/task_queues:77:11)',
}

Ранее была проблема с отправкой через API, проблема решилась заменой endpoint'a на
iot-data.api.cloud.yandex.net
вместо
iot-broker.api.cloud.yandex.net

Перезапрос токена не работает

Вот тут есть метод initialize:

    private async initialize() {
        if (this.token) {
            return;
        }

        let lastError = null;

        for (let i = 0; i < 5; i++) {
            try {
                // eslint-disable-next-line no-await-in-loop
                this.token = await this.fetchToken();
                break;
            } catch (error) {
                lastError = error;
            }
        }
        if (!this.token) {
            throw new Error(
                // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                `failed to fetch token from metadata service: ${lastError}`,
            );
        }
        setTimeout(async () => {
            try {
                this.token = await this.fetchToken();
            } catch {
                // TBD
            }
        }, 30_000);
    }

Думаю, что предполагалось, что каждые 30 секунд токен будет перезапрашиваться. Но setTimeout вызовет fetchToken только один раз. Тут не должен использоваться setInterval?

Update aws-sdk from v2 to v3 and save much space!

From aws blog:

The aws-sdk package adds about 40 MB to your application. Replacing varAWS = require("aws-sdk") with const {DynamoDB} = require("@aws-sdk/client-dynamodb") reduces that overhead to about 3 MB. Restricting the import to just the DynamoDB client and ListTablesCommand command reduces the overhead to less than 100 KB.

Как генерятся js/ts классы из proto файлов в этом репозитории?

Есть несколько тикетов про добавление новых сервисов (например #25 и #34), где кажется нужно просто сгенерить классы по существующим proto файлам. Я даже готов сделать пул-реквест. Но тут немного хитрая генерация, с разбивкой по файлам и добавлением кастомного кода. Можете рассказать, как устроена генерация?
Для сравнения, в ydb-nodejs-sdk скрипт генерации вот такой, и с ним гораздо проще законтрибьютить.

What happened to InvokeService in v2?

I used to call my private yandex function like so:

            const iamToken = ...;
            const session = new Session({ iamToken: iamToken });
         
            const invokeService = new InvokeService(session);
            const YANDEX_FUNC_ID = 'MY_FUNCTION_ID';

            const payload = {
                'httpMethod': 'GET',
                'multiValueQueryStringParameters': {PARAM1': 'PARAM1, PARAM2: 'PARAM2'},
                'body': {},
            };
            const resp = await invokeService.invoke(YANDEX_FUNC_ID, payload, config.yandex_function_tag);

Now, that InvokeService is vanished, what is the migration path from the code above to using @yandex-cloud/nodejs-sdk?

Filter by function name does not work

Filter by function name does not work in list() method.

nodejs: v10.16.1
yandex-cloud: v1.3.3

const { Session } = require('yandex-cloud');
const { FunctionService } = require('yandex-cloud/api/serverless/functions/v1');

const session = new Session({ iamToken: 'MY_TOKEN' });
const fs = new FunctionService(session);

(async () => {
  const { functions } = await fs.list({
    folderId: 'MY_FOLDER_ID',
    filter: `name=${MY_FUNCTION_NAME}` // does not throw an error without this string
  }); // throw an error
})();
{ Error: 13 INTERNAL: Internal
    at Object.exports.createStatusError (demo-yandex-sdk\node_modules\grpc\src\common.js:91:15)
    at Object.onReceiveStatus (demo-yandex-sdk\node_modules\grpc\src\client_interceptors.js:1209:28)
    at InterceptingListener._callNext (demo-yandex-sdk\node_modules\grpc\src\client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (demo-yandex-sdk\node_modules\grpc\src\client_interceptors.js:618:8)
    at callback (demo-yandex-sdk\node_modules\grpc\src\client_interceptors.js:847:24)
  code: 13,
  metadata: Metadata { _internal_repr: {}, flags: 0 },
  details: 'Internal' }

bug: Add to src/token-service/metadata-token-service.ts regular token updates

Right now the token is not renewed, and after 12 hours Iam token gets expired

Token needs to be refreshed every 1 hour (~10% of 12 hours as recommended in Iam documentation)

The refresh should be done at the time the token is requested. With timer based implementation, two problems arise:

  • It is not known when the objectmetadata-token-service.ts class object becomes unnecessary, so there is no a place where to clear a timer
  • In serverless functions a timer behaves specifically - it doesn't work at all between serverless function calls.

Битые импорты в yandex-cloud/contrib/google/protobuf/index.d.ts

##[error]node_modules/yandex-cloud/contrib/google/protobuf/index.d.ts(890,30): error TS2304: Cannot find name 'MapKeySpec'.
##[error]node_modules/yandex-cloud/contrib/google/protobuf/index.d.ts(1003,37): error TS2304: Cannot find name 'Operation'.
##[error]node_modules/yandex-cloud/contrib/google/protobuf/index.d.ts(1007,26): error TS2304: Cannot find name 'HttpRule'.
##[error]Process completed with exit code 1.

13 INTERNAL Ошибка при вызове FunctionService.List

Пытаюсь получить functionId по её name
Как и написано в коментах To get a function ID make a [FunctionService.List] request.

let functionListResponse = await functionService.list({
	folderId: inputs.folderId,
    filter: inputs.functionName
});

Текущее поведение:
При вызове постоянно выскакивает ошибка ##[error]13 INTERNAL: Internal

Ожидаемое поведение:
Возврат списка функций

[Вопрос] существует ли единый способ управления бессерверными решениями?

Прошу прощения за вопрос в issues. Всего два вопроса.

  1. @aws-sdk/lambda совместима в yandex functions?
  2. @yandex-cloud/nodejs-sdk умеет делать тоже самое, что и @aws-sdk-client-s3 + @aws-sdk/lambda?

Я вообще не могу загуглить инфу и найти хоть какие-то примеры по теме. Вообще ничего нет. Пытался сделать на текущей sdk и все закончилось головной болью от попытке разобраться с s3. Решил перейти на aws и за пау секунд сделал все, что было нужно. Дошел до функций и опять ступор. Очень надеюсь на помощь.

How to update docker image inside VM | Как обновить докер образ в ВМ

I'm looking for a way to automatically update docker image inside VM when new release available in Container registry.
I'm going to use Cloud Functions but can't seem to find a method in SDK that would update docker image the VM is using.

Example would be very appreciated.

=============================
Нужно настроить автоматическое обновление образа в докер контейнере, когда новая версия контейнера появляется в регистре.
Собираюсь использовать Cloud Functions, но нигде не могу найти метод, с помощью которого можно было бы обновить докер изображение в ВМ.

Поделитесь, пожалуйста, примером, как это сделать.

InvokeService.invoke returns empty response, yc serverless function invoke for the same function OK

Code example:

const { InvokeService } = require('yandex-cloud/lib/serverless/functions/v1/invoke');
const {Session}      = require('yandex-cloud');
const iamToken = await AIMTokenFactory.get(serviceAccountId, keyId, key);
const session = new Session({ iamToken: iamToken });
const invokeService = new InvokeService(session);
const payload = {action: 'get_tree_id_object_id_by_patient_or_tube',content: {tube_id: "XXXXX"}};
const resp = await invokeService.invoke(FUNCTION_ID, payload);
console.log(`resp ${resp}`);

output:

resp null

yc serverless function invoke FUNCTION_NAME -d '{"queryStringParameters": {"action": "get_tree_id_object_id_by_patient_or_tube", "content": {"tube_id": "XXXXX"}}}'

returns a valid response with data

Не понятен вывод createVersion

Я пытаюсь создавать новую версию облачной функции:

async function createVersion(content, functionId, runtime, serviceAccountId) {
  const functionService = session.client(serviceClients.FunctionServiceClient);
  const { serverless: { functions_function_service: { CreateFunctionVersionRequest } } } = cloudApi;
  const request = CreateFunctionVersionRequest.fromPartial({
            functionId,
            runtime,
            serviceAccountId,
  });
  request.content = content; // Buffer
  const operation = await functionService.createVersion(request);
  console.log(`Operation cmpleted: ${JSON.stringify(operation)`);
}

При этом в консоли я вижу вывод, но при этом operation.done === false и новая версия функции не создается.
Не очень понимаю, что происходит – если какая-то ошибка, то должно быть определено operation.err. Ну или await вызова createVersion не должен завершиться успешно 🤔. А так всё выглядит ок, но почему-то функция не создалась.

В логе операций стоит статус "ошибка".

То есть нужно трактовать done === false как неудачное создание функции?

Полный вывод результата createVersion:

{
    "$type": "yandex.cloud.operation.Operation",
    "id": "***",
    "description": "Create function version",
    "createdBy": "***",
    "done": false,
    "createdAt": "2023-01-16T23:43:19.860Z",
    "modifiedAt": "2023-01-16T23:43:19.860Z",
    "metadata": {
      "$type": "google.protobuf.Any",
      "typeUrl": "type.googleapis.com/yandex.cloud.serverless.functions.v1.CreateFunctionVersionMetadata",
      "value": {
        "type": "Buffer",
        "data": [
          10,
          20,
          100,
          52,
          101,
          50,
          54,
          99,
          56,
          97,
          116,
          113,
          105,
          116,
          98,
          54,
          51,
          111,
          115,
          114,
          52,
          110
        ]
      }
    }
  }

TypeError in `node_modules/@grpc/grpc-js/build/src/channel.js`

Может вы поможете разобраться, в чем же дело:)

Если комментирую TypeError тут node_modules/@grpc/grpc-js/build/src/channel.js, и оно работает, логи отправляются.

        if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {
			console.log(credentials);
			console.log(channel_credentials_1.ChannelCredentials);
            // throw new TypeError('Channel credentials must be a ChannelCredentials object');
        }

В консоли два объекта:

ComposedChannelCredentialsImpl {
  callCredentials: SingleCallCredentials { metadataGenerator: [Function (anonymous)] },
  channelCredentials: SecureChannelCredentialsImpl {
    callCredentials: EmptyCallCredentials {},
    rootCerts: null,
    privateKey: null,
    certChain: null,
    verifyOptions: {},
    connectionOptions: { secureContext: [SecureContext] }
  }
}
[class ChannelCredentials]
SecureChannelCredentialsImpl {
  callCredentials: EmptyCallCredentials {},
  rootCerts: null,
  privateKey: null,
  certChain: null,
  verifyOptions: {},
  connectionOptions: { secureContext: SecureContext { context: SecureContext {} } }
}
[class ChannelCredentials]

По удалял по одной все зависимости, пытаясь найти где же может быть коллизия. Но это не помогло:(

Originally posted by @pltnm239 in #50 (comment)

[Вопрос] Как покрыть типами serverless function handler

Добрый день! Подскажите, пожалуйста, как покрыть типами обработчик serverless-функции? Что указать в качестве типов аргументов event и context, а также, что указать в качестве возвращаемого значения? Спасибо!

import { CloudService } from "yandex-cloud/api/resourcemanager/v1";

export async function handler(event: any, context: any): any {
  const cloudService = new CloudService();
  const clouds = await cloudService.list({});

  return { clouds };
}

Как получить IAM токен для сервисного аккаунта без oauth / iam токена?

Чтобы использовать метод create, нужен подобный код:

import {Session} from 'yandex-cloud';
import {IamTokenService} from 'yandex-cloud/api/iam/v1';

const iamService = new IamTokenService(new Session({}));
const {iamToken} = await iamService.create({jwt: '...'});

Однако в подобном случае, так как в сессии нет ни одного токена, библиотека пытается сходить в http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token и получает ETIMEDOUT.
Как правильно, если у меня есть jwt токен? Напрямую по инструкции - получается.

AWS dependency

It is sad that you own samples uses AWS. Now it it clear that it is simplier just to use Node.js from original AWS SDK. Why you use AWS as a backend in samples? Or all your services maps to AWS in background? Strange.

No folderId parameter in llm APIs

TextGenerationServiceClient methods accept Request objects without folderId parameter which is actually required. This makes LLM apis impossible to use

ClientError: /speechkit.tts.v3.Synthesizer/UtteranceSynthesis UNIMPLEMENTED

My code is as following:

import { Session, serviceClients } from '@yandex-cloud/nodejs-sdk';
import { UtteranceSynthesisRequest } from '@yandex-cloud/nodejs-sdk/dist/generated/yandex/cloud/ai/tts/v3/tts';

const YANDEX_IAM_TOKEN = '...'

export async function tts() {
  const session = new Session({ iamToken: YANDEX_IAM_TOKEN });
  const client = session.client(serviceClients.SynthesizerClient);
  const req = UtteranceSynthesisRequest.fromPartial({
    text: 'Hello, world!',
  });
  for await (let item of client.utteranceSynthesis(req)) {
    console.log(item);
  }
}

However, it raises an exception:

ClientError: /speechkit.tts.v3.Synthesizer/UtteranceSynthesis UNIMPLEMENTED: 
    at wrapClientError (node_modules/nice-grpc/src/client/wrapClientError.ts:7:12)
    at Object.serverStreamingMethod [as next] (node_modules/nice-grpc/src/client/createServerStreamingMethod.ts:80:28)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

What I do wrong?

Проблема с созданием instance

Делаю по примеру

const operation = await instanceService.create({
      folderId,
      zoneId: TARGET_ZONE_ID,
      platformId: 'standard-v2',
      resourcesSpec: {
        memory: Long.fromNumber(2 * 1024 * 1024 * 1024),
        cores: Long.fromNumber(2),
      },
      bootDiskSpec: {
        autoDelete: true,
        diskSpec: {
          size: Long.fromNumber(10 * 1024 * 1024 * 1024),
          imageId: image.id,
        },
      },
      networkInterfaceSpecs: [
        {
          subnetId: subNetwork.id,
          primaryV4AddressSpec: {
            oneToOneNatSpec: {ipVersion: IpVersion.IPV4},
          },
        },
      ],
    });

получаю эксепшен

Response deserialization failed: Cannot read property 'google' of undefined
(node:37183) UnhandledPromiseRejectionWarning: Error: 13 INTERNAL: Failed to parse server response
    at Object.exports.createStatusError (/Users/ivan/projects/aggregion/enclave-service-ts/node_modules/grpc/src/common.js:91:15)
    at Object.onReceiveStatus (/Users/ivan/projects/aggregion/enclave-service-ts/node_modules/grpc/src/client_interceptors.js:1213:28)
    at InterceptingListener._callNext (/Users/ivan/projects/aggregion/enclave-service-ts/node_modules/grpc/src/client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (/Users/ivan/projects/aggregion/enclave-service-ts/node_modules/grpc/src/client_interceptors.js:618:8)
    at callback (/Users/ivan/projects/aggregion/enclave-service-ts/node_modules/grpc/src/client_interceptors.js:849:24)
(node:37183) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:37183) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Через консоль видно, что ВМ создается

Incorrect loggins service endpoints

@DavyJohnes
Кажется тут ошибка. https://github.com/yandex-cloud/nodejs-sdk/blob/alpha/src/service-endpoints.ts#L164-L169

{
        serviceIds: [
            'yandex.cloud.logging.v1.LogGroupService',
            'yandex.cloud.logging.v1.LogIngestionService',
            'yandex.cloud.logging.v1.LogReadingService',
        ],
        endpoint: 'logs.api.cloud.yandex.net:443',
    },

А должно быть как тут https://api.cloud.yandex.net/endpoints ingester.logging.yandexcloud.net:443

Originally posted by @nikolaymatrosov in #50 (comment)

Channel credentials must be a ChannelCredentials object

import {serviceClients, Session} from '@yandex-cloud/nodejs-sdk';

const session = new Session();
const logClient = session.client(serviceClients.LogIngestionServiceClient);

Ошибка:

/Users/vlad-kolotvin/podpison/backend/node_modules/nice-grpc/node_modules/@grpc/grpc-js/build/src/channel.js:81
            throw new TypeError('Channel credentials must be a ChannelCredentials object');
                  ^

TypeError: Channel credentials must be a ChannelCredentials object
    at new ChannelImplementation (/Users/vlad-kolotvin/podpison/backend/node_modules/nice-grpc/node_modules/@grpc/grpc-js/build/src/channel.js:81:19)
    at createChannel (/Users/vlad-kolotvin/podpison/backend/node_modules/nice-grpc/lib/client/channel.js:20:12)
    at Session.client (/Users/vlad-kolotvin/podpison/backend/node_modules/@yandex-cloud/nodejs-sdk/dist/session.js:65:55)
    at file:///Users/vlad-kolotvin/podpison/backend/src/logger.js:4:27
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
    at async loadESM (node:internal/process/esm_loader:85:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

Node.js v18.0.0

Кажется, что в зависимостях используются несовместимые версии grpc-js.

InstanceService update

С помощью метода update(InstanceService) пытаюсь изменить resources_spec.

В доках: "Поля, которые требуется изменить, указываются в запросе в поле update_mask".
В заголовках sdk прописан в camelCase как updateMask. Но если заполнять его как updateMask, то при выполнении пишет ошибку: UnhandledPromiseRejectionWarning: Error: 3 INVALID_ARGUMENT: Validation failed: - update_mask: Field mask cannot be empty Если поменять на 'update_mask', то начинает работать.

А далее основная проблема, в 'update_mask' надо указать поля, которые будут заменены. Главный вопрос, из каких доков по API яндекса брать названия, из REST(там поле называется "resourcesSpec") или из gRPC(там "resources_spec"), или так, как указано в ответе Operation(get/list, "resources")?

Задача, изменить resourcesSpec на что-то подобное:

resourcesSpec: {memory: 4, cores: 4, coreFraction: 100},

Это не срабатывает, опять же, не понятно, в каком именно формате указывать поля и значения. В ответ ошибка:
(node:2587) UnhandledPromiseRejectionWarning: Error: 3 INVALID_ARGUMENT: Request validation error: Unable to update selected parameters at once.

Можно посмотреть работающий пример метода update в рамках данного SDK?

Не получается сгенерировать iam-token по примеру из документации

В примере Получить IAM-токен с помощью JWT для nodejs

var jose = require('node-jose');
var fs = require('fs');

var key = fs.readFileSync(require.resolve('<файл_закрытого_ключа>'));

var serviceAccountId = '<идентификатор_сервисного_аккаунта>';
var keyId = '<идентификатор_открытого_ключа>';
var now = Math.floor(new Date().getTime() / 1000);

var payload = { aud: "https://iam.api.cloud.yandex.net/iam/v1/tokens",
                iss: serviceAccountId,
                iat: now,
                exp: now + 3600 };

jose.JWK.asKey(key, 'pem', { kid: keyId, alg: 'PS256' })
    .then(function(result) {
        jose.JWS.createSign({ format: 'compact' }, result)
            .update(JSON.stringify(payload))
            .final()
            .then(function(result) {
                // result — это сформированный JWT.
            });
    });

на строчке

jose.JWK.asKey(key, 'pem', { kid: keyId, alg: 'PS256' })

возникает ошибка -

return Promise.reject(new Error("unsupported key type"));

Как это исправить?

Severity vulnerability: Prototype Pollution in protobufjs

protobufjs <6.11.3
Severity: high
Prototype Pollution in protobufjs - GHSA-g954-5hwp-pp24
fix available via npm audit fix --force
Will install [email protected], which is a breaking change
node_modules/@yandex-cloud/nodejs-sdk/node_modules/protobufjs
@yandex-cloud/nodejs-sdk *
Depends on vulnerable versions of protobufjs
node_modules/@yandex-cloud/nodejs-sdk
ydb-sdk >=3.1.0
Depends on vulnerable versions of @yandex-cloud/nodejs-sdk
node_modules/ydb-sdk

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.