Таймер сработал, Azure Функция запускается, но не заканчивается? - PullRequest
0 голосов
/ 26 июня 2018

Я хочу использовать функцию Azure, запускаемую по таймеру, для генерации количества аксиальных пост-вызовов для изменения настройки пропускной способности ряда коллекций CosmosDB.

В соответствии с журналами запустится приведенный ниже код (т.е.появляется сообщение «[ Информация] Функция запущена »), но затем больше не регистрируется, и функция завершается с кодом состояния 202 Принято .

У меня естьподозрение, что проблема вызвана тем, как я выполняю обещания Axios, но после многих попыток я обращаюсь за помощью к Stackoverflow.

Любая помощь будет принята с благодарностью.

const axios = require("axios");
const azure = require("azure-storage");
const functionURL = "https://<redacted>.azurewebsites.net/api/ChangeRU?code=<redacted>"

// Update Offer for Collection
function updateOffer_for_Collection_RESTCall(
    environment,
    database,
    collection,
    newRU
) {
    context.log(`\nUpdate throughput for collection (${collection}) in database (${database}) of environment (${environment}) to: ${newRU}`);

    // Execute REST call
    const url = functionURL + "&env=" + environment + "&database=" + database + "&collection=" + collection + "&ru=" + newRU;
    context.log(`url = ${url}`);

    return url;
}

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();
    context.log('Scale down job started:', timeStamp);

    if (myTimer.isPastDue) {
        context.log('Scale down job is running late!');
    }

    var collectionTableService = azure.createTableService("<storageaccount>", "<redacted>");

    const query = new azure.TableQuery()
        .top(2)
        .where('PartitionKey eq ?', 'DBCollections');
    context.log('Query created...');

    collectionTableService.queryEntities('DBCollections', query, null, function (error, result, response) {
        if (!error) {
            // result.entries contains entities matching the query
            const collections = result.entries;
            let axiosArray = [];
            for (let collection of collections) {
                context.log("Collection: " + JSON.stringify(collection) + "\n");
                // Process collection
                let url = updateOffer_for_Collection_RESTCall(collection.environment._, collection.database._, collection.collection._, 400);
                let newPromise = axios({
                    method: 'post',
                    url: url,
                    data: {}
                });
                axiosArray.push(newPromise);
            };

            axios
                .all(axiosArray)
                .then(
                function (results) {
                    let temp = results.map(r => r.data);
                    context.log('submitted all axios calls');
                })
                .catch(error => { });
            context.done();
        } else {
            context.log('Error retrieving records from table DBCollections: ' + error);
            context.done();
        }
    });
};

1 Ответ

0 голосов
/ 29 июня 2018

Обретя лучшее понимание Обещаний Javascript за последние несколько дней, я готов ответить на свой вопрос :-)

Подумайте над следующим переписыванием:

// This Azure Function will change the request units setting of a number of Cosmos DB database collections at CSP <redacted>

// Use https://github.com/axios/axios as a REST client
const axios = require("axios");
const azure = require("azure-storage");
const functionURL =
    "https://<redacted>.azurewebsites.net/api/<redacted>?code=<redacted>";


module.exports = function (context, myTimer) {
    context.log("Going in...");

    function asyncPostURL(url) {
        return new Promise((resolve, reject) => {
            axios.post(url)
                .then(function (response) {
                    context.log(`POST response: status=${response.status}, data=${response.data}`);
                    resolve(response.data);
                })
                .catch(function (error) {
                    context.log(error);
                    reject(error);
                });
        });
    }


    // Create POST url  to update offer for collection
    function create_url(record) {
        const environment = record.environment._;
        const database = record.database._;
        const collection = record.collection._;
        const newRU = record.scaleupRU._;

        context.log(
            `\nUpdate throughput for collection (${collection}) in database (${database}) of environment (${environment}) to: ${newRU}`
        );

        // Create POST url
        const url =
            functionURL +
            "&env=" +
            environment +
            "&database=" +
            database +
            "&collection=" +
            collection +
            "&ru=" +
            newRU;
        context.log(`url: ${url}`);

        return url;
    }

    function post_urls(arr, final, context) {
        return arr.reduce((promise, record) => {
            return promise
                .then(result => {
                    let url = create_url(record);
                    context.log(`url: ${url}.`);
                    return asyncPostURL(url).then(result => final.push(result));
                })
                .catch(error => {
                    context.log(error);
                });
        }, Promise.resolve());
    }


    var timeStamp = new Date().toISOString();
    context.log("Scale down job started:", timeStamp);

    if (myTimer.isPastDue) {
        context.log("Scale down job is running late!");
    }

    var collectionTableService = azure.createTableService(
        "pbscsptoolsstorage",
        "<redacted>"
    );

    const query = new azure.TableQuery()
        //.top(2)
        .where("PartitionKey eq ?", "DBCollections");
    context.log("Query created...");

    const get_collections = tbl =>
        new Promise((resolve, reject) => {
            collectionTableService.queryEntities(tbl, query, null, function (
                error,
                result,
                response
            ) {
                if (!error) {
                    context.log(`# entries: ${result.entries.length}`);
                    resolve(result.entries);
                } else {
                    reject(error);
                }
            });
        });

    var final = [];
    get_collections("<redacted>").then(
        collections => {
            context.log(`# collections: ${collections.length}`);
            post_urls(collections, final, context).then(() => context.log(`FINAL RESULT is ${final}`))
                .then(() => context.done());
        },
        error => {
            context.log("Promise get_collections failed: ", error)
                .then(() => context.done());
        }
    )

};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...