@seeka-labs/cli-apps 3.5.2 → 3.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/index.js +47183 -0
  2. package/dist/index.js.map +7 -0
  3. package/dist/init-template/.gitlab-ci.yml +67 -0
  4. package/dist/init-template/.nvmrc +1 -0
  5. package/dist/init-template/README.md +27 -0
  6. package/dist/init-template/app/.eslintrc.cjs +13 -0
  7. package/dist/init-template/app/browser/README.md +1 -0
  8. package/dist/init-template/app/browser/package.json +37 -0
  9. package/dist/init-template/app/browser/scripts/esbuild/build-browser-plugin.mjs +130 -0
  10. package/dist/init-template/app/browser/scripts/esbuild/plugins/importAsGlobals.mjs +39 -0
  11. package/dist/init-template/app/browser/src/browser.ts +12 -0
  12. package/dist/init-template/app/browser/src/plugin/index.ts +61 -0
  13. package/dist/init-template/app/browser/tsconfig.json +34 -0
  14. package/dist/init-template/app/lib/package.json +46 -0
  15. package/dist/init-template/app/lib/src/index.ts +4 -0
  16. package/dist/init-template/app/lib/src/models/index.ts +29 -0
  17. package/dist/init-template/app/lib/src/validation/index.ts +14 -0
  18. package/dist/init-template/app/lib/tsconfig.json +22 -0
  19. package/dist/init-template/app/server-azurefunc/.eslintrc.cjs +4 -0
  20. package/dist/init-template/app/server-azurefunc/.funcignore +19 -0
  21. package/dist/init-template/app/server-azurefunc/README.md +105 -0
  22. package/dist/init-template/app/server-azurefunc/host.json +31 -0
  23. package/dist/init-template/app/server-azurefunc/local.settings.template.json +34 -0
  24. package/dist/init-template/app/server-azurefunc/package.json +67 -0
  25. package/dist/init-template/app/server-azurefunc/scripts/dev-queue-setup.js +55 -0
  26. package/dist/init-template/app/server-azurefunc/src/app/api/router.ts +14 -0
  27. package/dist/init-template/app/server-azurefunc/src/app/api/routes/getInstallationSettings.ts +13 -0
  28. package/dist/init-template/app/server-azurefunc/src/app/api/routes/setInstallationSettings.ts +35 -0
  29. package/dist/init-template/app/server-azurefunc/src/app/jobs/index.ts +61 -0
  30. package/dist/init-template/app/server-azurefunc/src/app/logging/index.ts +4 -0
  31. package/dist/init-template/app/server-azurefunc/src/app/models/index.ts +12 -0
  32. package/dist/init-template/app/server-azurefunc/src/app/services/activites.ts +8 -0
  33. package/dist/init-template/app/server-azurefunc/src/functions/healthCheck.ts +19 -0
  34. package/dist/init-template/app/server-azurefunc/src/functions/seekaAppWebhook.ts +202 -0
  35. package/dist/init-template/app/server-azurefunc/src/functions/trackActivityQueueHandler.ts +49 -0
  36. package/dist/init-template/app/server-azurefunc/src/functions/ui.ts +51 -0
  37. package/dist/init-template/app/server-azurefunc/tsconfig.json +24 -0
  38. package/dist/init-template/app/ui/README.md +40 -0
  39. package/dist/init-template/app/ui/index.html +21 -0
  40. package/dist/init-template/app/ui/package.json +72 -0
  41. package/dist/init-template/app/ui/public/favicon.ico +0 -0
  42. package/dist/init-template/app/ui/scripts/copy-output.mjs +30 -0
  43. package/dist/init-template/app/ui/src/App.tsx +72 -0
  44. package/dist/init-template/app/ui/src/assets/app-icon.svg +1 -0
  45. package/dist/init-template/app/ui/src/components/setup/steps/complete/index.tsx +32 -0
  46. package/dist/init-template/app/ui/src/components/setup/steps/first/index.tsx +27 -0
  47. package/dist/init-template/app/ui/src/components/setup/steps/index.tsx +22 -0
  48. package/dist/init-template/app/ui/src/components/setup/steps/second/index.tsx +38 -0
  49. package/dist/init-template/app/ui/src/index.tsx +45 -0
  50. package/dist/init-template/app/ui/src/routes/home/index.tsx +21 -0
  51. package/dist/init-template/app/ui/src/vite-env.d.ts +13 -0
  52. package/dist/init-template/app/ui/tsconfig.json +35 -0
  53. package/dist/init-template/app/ui/tsconfig.node.json +10 -0
  54. package/dist/init-template/app/ui/vite.config.mts +48 -0
  55. package/dist/init-template/package.json +44 -0
  56. package/dist/init-template/tsconfig.json +24 -0
  57. package/package.json +1 -1
  58. package/README.md +0 -1
@@ -0,0 +1,105 @@
1
+ # Seeka app - Azure functions
2
+
3
+ ## Development
4
+
5
+ - See [Configure your environment](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-typescript?pivots=nodejs-model-v4#configure-your-environment) for dependencies
6
+ - For emulating Azure storage queues, blobs and tables: `docker run --name azurite -p 10000:10000 -p 10001:10001 -p 10002:10002 --detach mcr.microsoft.com/azure-storage/azurite`
7
+ - Set `AzureWebJobsStorage` setting in local.settings.json to `UseDevelopmentStorage=true`
8
+ - If not using WSL:
9
+ `UseDevelopmentStorage=true`
10
+ - If using WSL, the following may be required to allow your app to reach Azure storage emulator:
11
+
12
+ Replace `MY-MACHINE-NAME` with your hostname. Below connection string allows running Azurite on your host machine and lets WSL connect to it
13
+ `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://MY-MACHINE-NAME.local:10000/devstoreaccount1;QueueEndpoint=http://MY-MACHINE-NAME.local:10001/devstoreaccount1;TableEndpoint=http://MY-MACHINE-NAME.local:10002/devstoreaccount1;`
14
+ - Install Azure Storage explorer and create your queues (see `./src/lib/jobs/index.ts` for `queueNames`). Azure Storage explorer can be used to view your queue items.
15
+ - `yarn install`
16
+ - `yarn dev`
17
+
18
+ ### Debugging
19
+ Supports VSCode debugging via the debugger and utilisation of breakpoints.
20
+ This is only tested on Linux but may work on Windows.
21
+ If using Windows then use WSL with an Ubuntu distro for support of attaching the VS code debugger
22
+
23
+ ### Live urls
24
+ You can expose your app locally to the internet via Ngrok to test your app before deploying.
25
+
26
+ #### Setup
27
+ 1. Sign up for a Ngrok account
28
+ 2. Get your auth token
29
+ 3. `yarn ngrok config add-authtoken [auth token here]` replacing `[auth token]` with the auth token retrieved from your Ngrok dashboard
30
+
31
+ #### Running
32
+ 1. `yarn start` OR start debugging in VSCode
33
+ 2. In separate terminal window run `yarn tunnel` and observe the log entry that starts with `Live url exposed`.
34
+ 3. Input the URL into your Seeka app configuration as the "Webook URL" via the Seeka UI.
35
+
36
+ ## Included example functions
37
+ ### Seeka app webhook
38
+ `src/functions/seekaAppWebhook.ts`
39
+
40
+ Handles inbound webhooks sent from Seeka to your app.
41
+
42
+ ### Queue example
43
+ `src/functions/queueExample.ts`
44
+
45
+ Handles taking a message and placing it on an Azure storage queue for later processing. This concept can be used to offload long running operations based on data sent to your app from Seeka and can help to ensure Azure Function time execution limits are respected.
46
+
47
+ ### Polling example
48
+ `src/functions/pollingExample.ts`
49
+
50
+ Handles scheduled invoking of a function. This concept can be used to "fan out" long running operations based on data sent to your app from Seeka and can help to ensure Azure Function time execution limits are respected by splitting long running operations into smaller, less time consuming parts.
51
+
52
+ ## Invoking functions
53
+ ### Development environment
54
+ Scheduled / timer function: `curl -i -d '{"input": null}' -H "Content-Type: application/json" -X POST http://localhost:7072/admin/functions/pollingExample`
55
+
56
+ ### Azure cloud
57
+ Scheduled / timer function: `curl -i -d '{"input": null}' -H "Content-Type: application/json" -H "x-functions-key: <key from azure portal>" -X POST https://example-app-name.azurewebsites.net/admin/functions/pollingExample`
58
+
59
+ See [this doc](https://learn.microsoft.com/en-us/azure/azure-functions/functions-manually-run-non-http?tabs=azure-portal#get-the-master-key) on how to get the functions (master) key
60
+
61
+ ## Logging
62
+ Centralised logging handled by [Winston](https://www.npmjs.com/package/winston). Winston is installed in this template and is also used in the Seeka SDK NPM packages.
63
+
64
+ [Seq](https://datalust.co/seq) Winston transport is installed in this template (optional).
65
+
66
+ To configure Seq options, see `_SEQ_` environment variables.
67
+
68
+ To install Seq on your development machine
69
+ 1. Run `docker run --name seq -d --restart=always -e ACCEPT_EULA=Y -p 5341:80 datalust/seq:2024.2`
70
+ 2. Update your `LOGGING_SEQ_SERVERURL` environment variable to `http://localhost:5341` or `http://[YOUR MACHINE NAME].local:5341` if using WSL.
71
+
72
+ If creating an API key for Seq, only permission that is required is `Ingest`.
73
+
74
+ ## State management
75
+ Installations of your app and other state required for your app to function is stored in Redis. Another state provider can be swapped out for Redis, see `src/lib/state/seeka/installations.ts` for the file that manages the state of the installations.
76
+
77
+ ### Upstash (optional)
78
+ If you dont want to use Upstash for Redis then the connection strings in `.env` can be swapped with your Redis instance.
79
+
80
+ > If using Upstash then create a database before following the below guide to deploying your AWS lambda function.
81
+
82
+ > When choosing region - use a region that is closest to the Azure region that your function app is hosted in to reduce latency between the function and the Redis database.
83
+
84
+ ## Deployment
85
+ This project comes ready to deploy for free to Azure functions with database backed by Redis hosted by Upstash and queues, blobs and tables backed by Azure Storage.
86
+
87
+ 1. Create Azure function app via the portal with below settings
88
+ - Function app name: example-app-name
89
+ - Code or container image: Code
90
+ - Runtime stack: Node.js
91
+ - Version: 18 LTS
92
+ - Region: Closest region to where your upstash "master / write" database is located
93
+ - Operating system: linux
94
+ - Hosting: Consumption
95
+ - Enable public access: On
96
+ 2. Set environment variables of the Azure web app - reference local.settings.json "Values"
97
+ 3. If your app receives calls directly from the browser (eg. your browser app plugin) then CORS needs to be enabled for all origins from within the settings of the Function app in Azure portal.
98
+ 3. `yarn deploy`
99
+
100
+ ### Continuous delivery
101
+ This template includes a GitLab CD pipeline that can be used to trigger deployments of your app when changes are pushed to your Git repository.
102
+
103
+ ## References
104
+ - https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite
105
+ - https://learn.microsoft.com/en-us/azure/storage/queues/storage-quickstart-queues-nodejs?tabs=connection-string%2Croles-azure-portal%2Cenvironment-variable-windows%2Csign-in-azure-cli
@@ -0,0 +1,31 @@
1
+ {
2
+ "version": "2.0",
3
+ "logging": {
4
+ "applicationInsights": {
5
+ "samplingSettings": {
6
+ "isEnabled": true,
7
+ "excludedTypes": "Request"
8
+ }
9
+ }
10
+ },
11
+ "extensions": {
12
+ "http": {
13
+ "routePrefix": ""
14
+ },
15
+ "queues": {
16
+ "batchSize": 32,
17
+ "newBatchThreshold": 8,
18
+ "maxDequeueCount": 1,
19
+ "visibilityTimeout": "00:00:30"
20
+ }
21
+ },
22
+ "functionTimeout": "00:10:00",
23
+ "extensionBundle": {
24
+ "id": "Microsoft.Azure.Functions.ExtensionBundle",
25
+ "version": "[4.*, 5.0.0)"
26
+ },
27
+ "concurrency": {
28
+ "dynamicConcurrencyEnabled": true,
29
+ "snapshotPersistenceEnabled": true
30
+ }
31
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "IsEncrypted": false,
3
+ "Host": {
4
+ "CORS": "*"
5
+ },
6
+ "Values": {
7
+ "FUNCTIONS_WORKER_RUNTIME": "node",
8
+ "FUNCTIONS_EXTENSION_VERSION": "~4",
9
+ "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
10
+ "SEEKA_DEBUG_ENABLED": "true",
11
+ "NODE_TLS_REJECT_UNAUTHORIZED": "0",
12
+ "REDIS_CONNECTION_USER": "default",
13
+ "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "",
14
+ "OTEL_EXPORTER_OTLP_LOGS_HEADERS": "",
15
+ "SEEKA_INGEST_URL": "",
16
+ "SEEKA_ISSUER_URL": "",
17
+ "SEEKA_APP_ID": "",
18
+ "SEEKA_APP_SECRET": "",
19
+ "REDIS_CONNECTION_HOST": "",
20
+ "REDIS_CONNECTION_PASSWORD": "",
21
+ "AzureWebJobsStorage": "",
22
+ "SEEKA_TELEMETRY_URL": "",
23
+ "REDIS_CONNECTION_PORT": "6379",
24
+ "REDIS_CONNECTION_TLS": "true",
25
+ "OTEL_LOG_LEVEL": "debug",
26
+ "LOGGING_LEVEL": "silly",
27
+ "SELF_HOST_BASEURL": "",
28
+ "APP_UI_BASE_PATH": "",
29
+ "OTEL_TRACES_EXPORTER": "none",
30
+ "OTEL_METRICS_EXPORTER": "none",
31
+ "OTEL_LOGS_EXPORTER": "none",
32
+ "OTEL_PROPAGATORS": "none"
33
+ }
34
+ }
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@example-org-name/example-app-name-server-azurefunc",
3
+ "version": "3.5.4",
4
+ "description": "Seeka Azure Serverless function app example-app-name",
5
+ "author": "Seeka <administrator@seeka.co>",
6
+ "license": "MIT",
7
+ "main": "dist/src/functions/*.js",
8
+ "private": true,
9
+ "engines": {
10
+ "node": ">=22"
11
+ },
12
+ "scripts": {
13
+ "lint": "eslint",
14
+ "typecheck": "tsc --noEmit",
15
+ "build": "tsc",
16
+ "watch": "tsc -w",
17
+ "clean": "rimraf dist",
18
+ "prestart": "yarn build",
19
+ "dev": "func start --port 7072",
20
+ "tunnel": "ngrok http 7072 --hostname=seeka-app-example-app-name-localdev.au.ngrok.io --region au --log=stdout --log-format=term",
21
+ "deploy": "func azure functionapp publish example-app-name --no-build --javascript",
22
+ "dev:queue:create": "node scripts/dev-queue-setup.js activity-track-queue && node scripts/dev-queue-setup.js activity-track-queue-poison"
23
+ },
24
+ "dependencies": {
25
+ "@azure/functions": "^4",
26
+ "@azure/storage-queue": "^12",
27
+ "@example-org-name/example-app-name-lib": "workspace:*",
28
+ "@opentelemetry/api": "^1",
29
+ "@opentelemetry/exporter-logs-otlp-proto": "^0",
30
+ "@opentelemetry/exporter-trace-otlp-proto": "^0",
31
+ "@opentelemetry/instrumentation-grpc": "^0",
32
+ "@opentelemetry/instrumentation-http": "^0",
33
+ "@opentelemetry/instrumentation-ioredis": "^0",
34
+ "@opentelemetry/instrumentation-net": "^0",
35
+ "@opentelemetry/instrumentation-undici": "^0",
36
+ "@opentelemetry/instrumentation-winston": "^0",
37
+ "@opentelemetry/sdk-node": "^0",
38
+ "@opentelemetry/sdk-trace-node": "^2",
39
+ "@opentelemetry/winston-transport": "^0",
40
+ "@redis/client": "^5",
41
+ "@redis/json": "^5",
42
+ "@seeka-labs/sdk-apps-core": "../../../workspace:* || ^3",
43
+ "@seeka-labs/sdk-apps-server": "../../../workspace:* || ^3",
44
+ "@seeka-labs/sdk-apps-server-host": "../../../workspace:* || ^3",
45
+ "@seeka-labs/sdk-apps-server-telemetry-core": "../../../workspace:* || ^3",
46
+ "@seeka-labs/sdk-apps-server-telemetry-logging": "../../../workspace:* || ^3",
47
+ "axios": "^1",
48
+ "jsonwebtoken": "^9",
49
+ "lodash-es": "^4",
50
+ "memory-cache": "^0",
51
+ "openid-client": "^6",
52
+ "redis": "^5",
53
+ "undici": "^7",
54
+ "winston": "^3",
55
+ "yup": "^1"
56
+ },
57
+ "devDependencies": {
58
+ "@types/jsonwebtoken": "^9",
59
+ "@types/lodash-es": "^4",
60
+ "@types/node": "^22",
61
+ "@typescript-eslint/eslint-plugin": "^8",
62
+ "@typescript-eslint/parser": "^8",
63
+ "eslint": "^9",
64
+ "rimraf": "^6",
65
+ "typescript": "^5"
66
+ }
67
+ }
@@ -0,0 +1,55 @@
1
+ /* eslint-disable @typescript-eslint/no-var-requires */
2
+ /* eslint-disable no-undef */
3
+ const { QueueClient } = require("@azure/storage-queue");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+
7
+ function getAzureWebJobsStorageConnectionString() {
8
+ // local.settings.json lives one level above this script (../local.settings.json)
9
+ const localSettingsPath = path.join(__dirname, "..", "local.settings.json");
10
+
11
+ let raw;
12
+ try {
13
+ raw = fs.readFileSync(localSettingsPath, "utf8");
14
+ }
15
+ catch (e) {
16
+ throw new Error(
17
+ `Unable to read ${localSettingsPath}. Ensure local.settings.json exists and is readable. Original error: ${e && e.message ? e.message : e}`
18
+ );
19
+ }
20
+
21
+ let json;
22
+ try {
23
+ json = JSON.parse(raw);
24
+ }
25
+ catch (e) {
26
+ throw new Error(
27
+ `Invalid JSON in ${localSettingsPath}. Original error: ${e && e.message ? e.message : e}`
28
+ );
29
+ }
30
+
31
+ const connectionString = json?.Values?.AzureWebJobsStorage;
32
+ if (typeof connectionString !== "string" || connectionString.trim() === "") {
33
+ throw new Error(
34
+ `Missing or empty Values.AzureWebJobsStorage in ${localSettingsPath}`
35
+ );
36
+ }
37
+
38
+ return connectionString;
39
+ }
40
+
41
+ (async function () {
42
+ // https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cqueue-storage#azure-sdks
43
+ // Dev / emulator / azurite
44
+ const connectionString = getAzureWebJobsStorageConnectionString();
45
+ var client = new QueueClient(
46
+ connectionString, process.argv[2]
47
+ );
48
+ const res = await client.createIfNotExists();
49
+ if (res.succeeded) {
50
+ console.log("Queue created - " + process.argv[2]);
51
+ }
52
+ else {
53
+ console.log("Queue already exists - " + process.argv[2]);
54
+ }
55
+ })();
@@ -0,0 +1,14 @@
1
+ import {ExampleAppAppInstallContext, ExampleAppAppInstallState} from "@example-org-name/example-app-name-lib";
2
+ import {getInstallationSettings} from "./routes/getInstallationSettings";
3
+ import {setInstallationSettings} from "./routes/setInstallationSettings";
4
+ import { SeekaAppInstallContext } from "@seeka-labs/sdk-apps-core";
5
+ import { Logger } from "winston";
6
+ import { AppUiHttpRequestResponse, HttpMethod } from "@seeka-labs/sdk-apps-server-host";
7
+ import {HttpRequest, InvocationContext} from "@azure/functions";
8
+
9
+ export const apiRouteHandler = async (req: HttpRequest, context: InvocationContext, requestedPath: string, requestedMethod: HttpMethod, installation: ExampleAppAppInstallContext, logger: Logger ): Promise<AppUiHttpRequestResponse | null> => {
10
+ if (requestedPath === '/api/settings' && requestedMethod === 'GET') return await getInstallationSettings(installation, req, context, logger);
11
+ if (requestedPath === '/api/settings' && requestedMethod === 'POST') return await setInstallationSettings(installation, req, context, logger);
12
+
13
+ return null;
14
+ }
@@ -0,0 +1,13 @@
1
+ import { HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
2
+ import { ExampleAppAppInstallContext, ExampleAppAppInstallSettings } from "@example-org-name/example-app-name-lib";
3
+ import { AppUiHttpRequestResponse } from "@seeka-labs/sdk-apps-server-host";
4
+ import { Logger } from "winston";
5
+
6
+ export const getInstallationSettings = async (installation: ExampleAppAppInstallContext, req: HttpRequest, context: InvocationContext, logger: Logger): Promise<AppUiHttpRequestResponse> => {
7
+ // Important to not expose any sensitive data to the client via this endpoint
8
+ // Be selective, no spread operator here, only the fields you want to expose
9
+ return {
10
+ status: 200,
11
+ jsonBody: installation.installationState?.installationSettings as ExampleAppAppInstallSettings
12
+ }
13
+ }
@@ -0,0 +1,35 @@
1
+ import { HttpRequest, InvocationContext } from "@azure/functions";
2
+ import { Logger } from "winston";
3
+
4
+ import { ExampleAppAppInstallContext, ExampleAppAppInstallSettings, validateInstallationSettings } from "@example-org-name/example-app-name-lib";
5
+ import { AppUiHttpRequestResponse, createOrUpdateInstallation } from "@seeka-labs/sdk-apps-server-host";
6
+
7
+ export const setInstallationSettings = async (installation: ExampleAppAppInstallContext, req: HttpRequest, context: InvocationContext, logger: Logger): Promise<AppUiHttpRequestResponse> => {
8
+ // Validate
9
+ const newSettings = (await req.json()) as ExampleAppAppInstallSettings | null;
10
+ if (!newSettings) {
11
+ return {
12
+ status: 400,
13
+ jsonBody: { error: 'Settings are required' }
14
+ };
15
+ }
16
+
17
+ const error = await validateInstallationSettings(newSettings, logger);
18
+ if (error) return {
19
+ status: 400,
20
+ jsonBody: { error }
21
+ }
22
+
23
+ installation.installationState = {
24
+ ...installation.installationState,
25
+ installationSettings: {
26
+ ...installation.installationState.installationSettings,
27
+ ...newSettings
28
+ }
29
+ };
30
+ await createOrUpdateInstallation(installation, logger);
31
+
32
+ return {
33
+ status: 200
34
+ };
35
+ }
@@ -0,0 +1,61 @@
1
+ import { QueueClient, QueueSendMessageOptions } from '@azure/storage-queue';
2
+ import type { Logger } from 'winston';
3
+ import {BackgroundJobRequestContext} from "@seeka-labs/sdk-apps-server-host";
4
+
5
+ export const queueNames = {
6
+ trackActivity: 'activity-track-queue',
7
+ }
8
+
9
+ export const triggerBackgroundJob = async <TPayload>(queueName: string, context: BackgroundJobRequestContext<TPayload>, logger: Logger, queueSendOptions?: QueueSendMessageOptions): Promise<void> => {
10
+ const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, queueName);
11
+ return await triggerBackgroundJobWithQueue(queueClient, context, logger, queueSendOptions);
12
+ }
13
+
14
+ const serialiseQueuePayload = (payload: unknown): string => {
15
+ const jsonString = JSON.stringify(payload)
16
+ return Buffer.from(jsonString).toString('base64')
17
+ }
18
+
19
+ export const deserialiseQueuePayload = <TPayload>(payload: string): TPayload => {
20
+ const jsonString = Buffer.from(payload, 'base64').toString()
21
+ return JSON.parse(jsonString) as TPayload;
22
+ }
23
+
24
+ export const triggerBackgroundJobWithQueue = async <TPayload>(queueClient: QueueClient, context: BackgroundJobRequestContext<TPayload>, logger: Logger, queueSendOptions?: QueueSendMessageOptions): Promise<void> => {
25
+ const body = {
26
+ ...context
27
+ }
28
+ const bodyStr = serialiseQueuePayload(body);
29
+
30
+ const response = await queueClient.sendMessage(bodyStr, queueSendOptions);
31
+
32
+ if (response.errorCode) {
33
+ const { requestId, date, errorCode } = response;
34
+ logger.error("Failed to trigger background job", { body, requestId, date, errorCode })
35
+ throw new Error(`Failed to trigger background job: ${response.errorCode}`);
36
+ }
37
+ else {
38
+ logger.info("Background job triggered for " + queueClient.name, { body, messageId: response.messageId, context })
39
+ }
40
+ }
41
+
42
+ export const sendQueueMessageToPoisonQueue = async <TPayload>(queueName: string, context: BackgroundJobRequestContext<TPayload>, logger: Logger): Promise<void> => {
43
+ const body = {
44
+ ...context
45
+ }
46
+ const bodyStr = serialiseQueuePayload(body);
47
+
48
+ // https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv5&pivots=programming-language-typescript#poison-messages
49
+ const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, `${queueName}-poison`);
50
+
51
+ const response = await queueClient.sendMessage(bodyStr, { messageTimeToLive: -1 });
52
+
53
+ if (response.errorCode) {
54
+ const { requestId, date, errorCode } = response;
55
+ logger.error("Failed to push to poison queue", { body, requestId, date, errorCode })
56
+ throw new Error(`Failed to push to poison queue: ${response.errorCode}`);
57
+ }
58
+ else {
59
+ logger.verbose("Message pushed to poison queue", { body, messageId: response.messageId, context })
60
+ }
61
+ }
@@ -0,0 +1,4 @@
1
+ import * as packageJson from '../../../package.json';
2
+ import {registerSeekaAppOpenTelemetry} from "@seeka-labs/sdk-apps-server-telemetry-logging";
3
+
4
+ registerSeekaAppOpenTelemetry(packageJson.name, packageJson.version, 'azure', 'azure_function', process.env);
@@ -0,0 +1,12 @@
1
+ 
2
+ import {SeekaActivityAcceptedWebhookContent} from "@seeka-labs/sdk-apps-server";
3
+ import { BackgroundJobRequestContext } from "@seeka-labs/sdk-apps-server-host";
4
+
5
+ export type TrackExampleAppActivityQueueItem = BackgroundJobRequestContext<TrackSeekaExampleAppActivityPayload> & {
6
+
7
+ }
8
+
9
+ export type TrackSeekaExampleAppActivityPayload = {
10
+ seekaActivity: SeekaActivityAcceptedWebhookContent
11
+ }
12
+
@@ -0,0 +1,8 @@
1
+ 
2
+ import {Logger} from "winston";
3
+ import {TrackSeekaExampleAppActivityPayload} from "../models";
4
+ import {SeekaAppInstallContext} from "@seeka-labs/sdk-apps-core";
5
+
6
+ export const sendActivityToAnotherSoftware = async (payload: TrackSeekaExampleAppActivityPayload, installation: SeekaAppInstallContext<any>, causationId: string, correlationId: string, logger: Logger): Promise<void> => {
7
+ // Anything
8
+ }
@@ -0,0 +1,19 @@
1
+ import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
2
+ import '../app/logging'
3
+ import { appLogger } from "@seeka-labs/sdk-apps-server-host";
4
+
5
+ app.http('healthCheck', {
6
+ methods: ['GET', 'HEAD'],
7
+ authLevel: 'anonymous',
8
+ route: 'api/health',
9
+ handler: healthCheck
10
+ });
11
+
12
+ export async function healthCheck(req: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
13
+ // logger.verbose('Health check request received', { status: res.status, url: req.url });
14
+ appLogger.verbose('Health check', { url: req.url });
15
+
16
+ return {
17
+ status: 200
18
+ }
19
+ }