Функция Azure, запускаемая webhook, выполняет действие по составлению списка исторических событий. - PullRequest
0 голосов
/ 08 января 2019

Веб-крючок настроен на запуск функции JavaScript Azure, которая выполняет действие. При тестировании одно событие webhook запускает одно выполнение функции Azure, выполняя действие только для этого события. Это желаемое поведение.

Однако, когда функция Azure активирована в пользовательском интерфейсе Azure, функция выполняется с заданными интервалами (каждые 5 минут, похоже), выполняя действие не только для самого последнего события webhook, но и для всех предыдущих событий webhook , Это поведение повторяется, даже если в течение последнего интервала не произошло ни одного события. Другими словами, каждые 5 минут действие выполняется для всех событий, которые когда-либо происходили. Это также верно, когда я тестирую в пользовательском интерфейсе, используя тот же код, который я тестирую локально.

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

function.json:

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

Спасибо за любые идеи.


Редактировать

Код функции:

module.exports = function (context, data) {
    var json = data.body;

    var request = require('request');

    // Parse the webhook event JSON body

    var unparsedEvents = json.events;
    for (let event of unparsedEvents) {
        var ContentId = event.EventData.ContentId;
        var ContentTypeId = event.EventData.ContentTypeId;
        var CommentId = event.EventData.CommentId;
        var options = new Object();

        if (CommentId) {
            options.url = "<url>" + CommentId + ".json";
            options.headers = {
                "Rest-User-Token": "<token>",
                "Content-Type": "application/json",
            };
        } else {
            options.url = "<url>" + ContentId + "/" + ContentTypeId + ".json";
            options.headers = {
                "Rest-User-Token": "<token>",
                "Content-Type": "application/json",
            };
        }

        function callback(error, response, body) {
            if (!error && response.statusCode == 200) {
                var info = JSON.parse(body);

                //For all content types but comments

                var username, profileUrl, subject, url, text;
                if (info.hasOwnProperty('Content')) {

                    username = info.Content.CreatedByUser.Username;
                    profileUrl = info.Content.CreatedByUser.ProfileUrl;
                    subject = info.Content.HtmlName;
                    url = info.Content.Url;
                    text = info.Content.HtmlDescription;
                };

                //For comments

                if (info.hasOwnProperty('Comment')) {

                    username = info.Comment.User.DisplayName;
                    profileUrl = info.Comment.User.ProfileUrl;
                    subject = info.Comment.Content.HtmlName;
                    url = info.Comment.Url;
                    text = info.Comment.Body;
                };
            };

            //Send to Slack

            function sendToSlack(theUsername, theIconEmoji) {

                var theUsername = "Bot";
                var theIconEmoji = ":bot:";

                var payload = {
                    attachments: [{
                        author_name: username,
                        author_link: profileUrl,
                        title: subject,
                        title_link: url,
                        text: text
                    }]
                };
                if (theUsername !== undefined) {
                    payload.username = theUsername;
                }
                if (theIconEmoji !== undefined) {
                    payload.icon_emoji = theIconEmoji;
                }
                var theRequest = {
                    url: urlWebHook,
                    method: "POST",
                    json: payload
                };
                request(theRequest, function (error, response, body) {});
            }

            var urlWebHook = "https://hooks.slack.com/services/<Id>";

            sendToSlack();
        };
    };
    request(options, callback);
};

host.json

{
  "version": "2.0",
  "functionTimeout": "00:01:00",
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "Function.<function>": "Debug",
      "default": "Debug"
    }
  },
  "watchDirectories": [
    "Shared"
  ]
}

Некоторые журналы ошибок:

Timeout value of 00:01:00 was exceeded by function
2019-01-09T22:44:10.513 [Debug] Hosting stopping
2019-01-09T22:44:10.514 [Information] Stopping JobHost
2019-01-09T22:44:10.520 [Information] Job host stopped
2019-01-09T22:44:10.520 [Debug] Hosting stopped
2019-01-09T22:44:34.217 [Debug] Workers Directory set to: D:\Program Files (x86)\SiteExtensions\Functions\2.0.12246\32bit\workers
2019-01-09T22:44:34.411 [Debug] Found worker config: D:\Program Files (x86)\SiteExtensions\Functions\2.0.12246\32bit\workers\java\worker.config.json
2019-01-09T22:44:34.413 [Debug] Will load worker provider for language: java
2019-01-09T22:44:34.413 [Debug] Found worker config: D:\Program Files (x86)\SiteExtensions\Functions\2.0.12246\32bit\workers\node\worker.config.json
2019-01-09T22:44:34.414 [Debug] Will load worker provider for language: node
2019-01-09T22:44:34.414 [Debug] Worker path for language worker java: D:\Program Files (x86)\SiteExtensions\Functions\2.0.12246\32bit\workers\java
2019-01-09T22:44:34.414 [Debug] Worker path for language worker node: D:\Program Files (x86)\SiteExtensions\Functions\2.0.12246\32bit\workers\node
2019-01-09T22:44:35.070 [Information] Initializing Host.
2019-01-09T22:44:35.071 [Information] Host initialization: ConsecutiveErrors=0, StartupCount=1
2019-01-09T22:44:35.073 [Debug] Hosting starting
2019-01-09T22:44:35.103 [Information] Starting JobHost
2019-01-09T22:44:35.111 [Information] Starting Host (HostId=<webhook name>, InstanceId=<id>, Version=2.0.12246.0, ProcessId=11704, AppDomainId=1, InDebugMode=True, InDiagnosticMode=False, FunctionsExtensionVersion=~2)
2019-01-09T22:44:35.171 [Information] Loading functions metadata
2019-01-09T22:44:35.319 [Information] 1 functions loaded
2019-01-09T22:44:35.441 [Information] Loading proxies metadata
2019-01-09T22:44:35.443 [Information] Initializing Azure Function proxies
2019-01-09T22:44:36.083 [Information] 0 proxies loaded
2019-01-09T22:44:36.164 [Debug] Adding Function descriptor provider for language node.
2019-01-09T22:44:36.164 [Debug] Creating function descriptors.
2019-01-09T22:44:36.205 [Debug] Function descriptors created.
2019-01-09T22:44:36.206 [Information] Generating 1 job function(s)
2019-01-09T22:44:36.275 [Information] Found the following functions:
Host.Functions.<webhook>
2019-01-09T22:44:36.276 [Information] Host initialized (1164ms)
2019-01-09T22:44:36.284 [Information] Host started (1172ms)
2019-01-09T22:44:36.285 [Information] Job host started
2019-01-09T22:44:36      Error occurred, type: error, text: The process cannot access the file 'D:\home\LogFiles\Application\Functions\Host\2019-01-09T21-43-54Z-a14e0af183.log' because it is being used by another process., stackTrace:    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at Kudu.Services.Performance.LogStreamManager.GetChanges(FileSystemEventArgs e) in C:\Kudu Files\Private\src\master\Kudu.Services\Diagnostics\LogStreamManager.cs:line 374
   at Kudu.Services.Performance.LogStreamManager.<>c__DisplayClass28_1.<OnChanged>b__0() in C:\Kudu Files\Private\src\master\Kudu.Services\
Diagnostics\LogStreamManager.cs:line 258
   at Kudu.Core.Infrastructure.OperationManager.<>c__DisplayClass2_0.<Attempt>b__0() in C:\Kudu Files\Private\src\master\Kudu.Core\Infrastructure\OperationManager.cs:line 16
   at Kudu.Core.Infrastructure.OperationManager.Attempt[T](Func`1 action, Int32 retries, Int32 delayBeforeRetry, Func`2 shouldRetry) in C:\Kudu Files\Private\src\master\Kudu.Core\Infrastructure\OperationManager.cs:line 42
   at Kudu.Core.Infrastructure.OperationManager.Attempt(Action action, Int32 retries, Int32 delayBeforeRetry) in C:\Kudu Files\Private\src\master\Kudu.Core\Infrastructure\OperationManager.cs:line 14
   at Kudu.Services.Performance.LogStreamManager.OnChanged(Object sender, FileSystemEventArgs e) in C:\Kudu Files\Private\src\master\Kudu.Services\Diagnostics\LogStreamManager.cs:line 256
   at Kudu.Services.Performance.LogStreamManager.<>c__DisplayClass27_0`2.<DoSafeAction>b__0(T1 t1, T2 t2) in C:\Kudu Files\Private\src\master\Kudu.Services\Diagnostics\LogStreamManager.cs:line 233
2019-01-09T22:44:36.554 [Debug] Debug file watch initialized.
2019-01-09T22:44:36.560 [Debug] Diagnostic file watch initialized.
2019-01-09T22:44:36.562 [Debug] File event source initialized.
2019-01-09T22:44:36.563 [Debug] Hosting started
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...