diff --git a/docs/generated/api.json b/docs/generated/api.json index 0bf0410a0..bc9797724 100644 --- a/docs/generated/api.json +++ b/docs/generated/api.json @@ -577,6 +577,27 @@ }, "releaseTag": "Public", "name": "PubSub" + }, + { + "kind": "EnumMember", + "canonicalReference": "@openfunction/functions-framework!ComponentType.State:member", + "docComment": "/**\n * The state type\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "State = " + }, + { + "kind": "Content", + "text": "\"state\"" + } + ], + "initializerTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "releaseTag": "Public", + "name": "State" } ] }, @@ -826,6 +847,54 @@ ], "isOptional": false, "name": "IsPubSubComponent" + }, + { + "kind": "Method", + "canonicalReference": "@openfunction/functions-framework!ContextUtils.IsStateComponent:member(1)", + "docComment": "/**\n * Checks if the component is a state component.\n *\n * @param component - The component to check.\n *\n * @returns A boolean value.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "static IsStateComponent(component: " + }, + { + "kind": "Reference", + "text": "OpenFunctionComponent", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionComponent:interface" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Content", + "text": "boolean" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isStatic": true, + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 4 + }, + "releaseTag": "Public", + "isProtected": false, + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "component", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "isOptional": false, + "name": "IsStateComponent" } ], "implementsTokenRanges": [] @@ -2051,6 +2120,47 @@ "endIndex": 12 } }, + { + "kind": "PropertySignature", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionContext#states:member", + "docComment": "/**\n * Optional state store config;\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "states?: " + }, + { + "kind": "Reference", + "text": "Record", + "canonicalReference": "!Record:type" + }, + { + "kind": "Content", + "text": "" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": true, + "releaseTag": "Public", + "name": "states", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 5 + } + }, { "kind": "PropertySignature", "canonicalReference": "@openfunction/functions-framework!OpenFunctionContext#version:member", @@ -2635,6 +2745,36 @@ "isStatic": false, "isProtected": false }, + { + "kind": "Property", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionRuntime#state:member", + "docComment": "/**\n * The promise that handle data by state store.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "abstract get state(): " + }, + { + "kind": "Reference", + "text": "StateOperations", + "canonicalReference": "@openfunction/functions-framework!~StateOperations:interface" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": true, + "isOptional": false, + "releaseTag": "Public", + "name": "state", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isStatic": false, + "isProtected": false + }, { "kind": "Property", "canonicalReference": "@openfunction/functions-framework!OpenFunctionRuntime#trigger:member", diff --git a/docs/generated/api.md b/docs/generated/api.md index 2fe1b49cc..11f211478 100644 --- a/docs/generated/api.md +++ b/docs/generated/api.md @@ -9,10 +9,12 @@ import { CloudEventV1 as CloudEvent } from 'cloudevents'; import { IndexedFieldWithPossiblyUndefined } from 'lodash'; +import { KeyValueType } from '@dapr/dapr/types/KeyValue.type'; import { ParamsDictionary } from 'express-serve-static-core'; import { ParsedQs } from 'qs'; import { Request as Request_3 } from 'express'; import { Response as Response_2 } from 'express'; +import { StateQueryResponseType } from '@dapr/dapr/types/state/StateQueryResponse.type'; export { CloudEvent } @@ -44,7 +46,8 @@ export interface CloudFunctionsContext { // @public export enum ComponentType { Binding = "bindings", - PubSub = "pubsub" + PubSub = "pubsub", + State = "state" } // @public @@ -56,6 +59,7 @@ export class ContextUtils { static IsBindingComponent(component: OpenFunctionComponent): boolean; static IsKnativeRuntime(context: OpenFunctionContext): boolean; static IsPubSubComponent(component: OpenFunctionComponent): boolean; + static IsStateComponent(component: OpenFunctionComponent): boolean; } // @public @@ -136,6 +140,7 @@ export interface OpenFunctionContext { postPlugins?: string[]; prePlugins?: string[]; runtime: `${RuntimeType}` | `${Capitalize}` | `${Uppercase}`; + states?: Record; version: string; } @@ -156,6 +161,8 @@ export abstract class OpenFunctionRuntime { HTTP: string; GRPC: string; }; + // Warning: (ae-forgotten-export) The symbol "StateOperations" needs to be exported by the entry point index.d.ts + abstract get state(): StateOperations; // Warning: (ae-forgotten-export) The symbol "OpenFunctionTrigger" needs to be exported by the entry point index.d.ts protected trigger?: OpenFunctionTrigger; static WrapUserFunction(userFunction: OpenFunction, context: OpenFunctionContext | OpenFunctionRuntime): (data: any) => Promise; diff --git a/src/openfunction/context.ts b/src/openfunction/context.ts index 15c665490..173f2fdc9 100644 --- a/src/openfunction/context.ts +++ b/src/openfunction/context.ts @@ -30,6 +30,10 @@ export interface OpenFunctionContext { * Optional output binding object. */ outputs?: Record; + /** + * Optional state store config; + */ + states?: Record; /** * Optional plugins to be executed before user function. */ @@ -99,6 +103,10 @@ export enum ComponentType { * The pubsub type. */ PubSub = 'pubsub', + /** + * The state type + */ + State = 'state', } /** @@ -139,6 +147,14 @@ export class ContextUtils { static IsPubSubComponent(component: OpenFunctionComponent): boolean { return component?.componentType.split('.')[0] === ComponentType.PubSub; } + /** + * Checks if the component is a state component. + * @param component - The component to check. + * @returns A boolean value. + */ + static IsStateComponent(component: OpenFunctionComponent): boolean { + return component?.componentType.split('.')[0] === ComponentType.State; + } } /** diff --git a/src/openfunction/runtime.ts b/src/openfunction/runtime.ts index b990c2ecb..8730602ac 100644 --- a/src/openfunction/runtime.ts +++ b/src/openfunction/runtime.ts @@ -1,8 +1,24 @@ import {env} from 'process'; -import {chain, get, has, extend, isPlainObject} from 'lodash'; +import { + chain, + get, + has, + extend, + isPlainObject, + isEmpty, + size, + values, +} from 'lodash'; import {Request, Response} from 'express'; + import {DaprClient, CommunicationProtocolEnum} from '@dapr/dapr'; +import {KeyValuePairType} from '@dapr/dapr/types/KeyValuePair.type'; +import {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; +import {OperationType} from '@dapr/dapr/types/Operation.type'; +import {IRequestMetadata} from '@dapr/dapr/types/RequestMetadata.type'; +import {StateQueryType} from '@dapr/dapr/types/state/StateQuery.type'; +import {StateQueryResponseType} from '@dapr/dapr/types/state/StateQueryResponse.type'; import {OpenFunction} from '../functions'; @@ -184,6 +200,24 @@ export abstract class OpenFunctionRuntime { * The promise that send data to certain ouput. */ abstract send(data: object, output?: string): Promise; + + /** + * The promise that handle data by state store. + */ + abstract get state(): StateOperations; +} + +/** + * The state's operation. + * @public + */ +export interface StateOperations { + save: (data: object, db?: string) => Promise; + get: (data: object, db?: string) => Promise; + getBulk: (data: object, db?: string) => Promise; + delete: (data: object, db?: string) => Promise; + transaction: (data: object, db?: string) => Promise; + query: (query: object, db?: string) => Promise; } /** @@ -243,4 +277,142 @@ class DaprRuntime extends OpenFunctionRuntime { return Promise.allSettled(actions); } + + /** + * Get the state store + * @param db the user specify the state store + * @returns Corresponding state store + */ + getState(db?: string): OpenFunctionComponent { + // check the states field + if (isEmpty(this.context.states)) { + throw new Error('You must specify the state in the context'); + } + + // if you don't specify the db, we will use the first one defined in the context + if (isEmpty(db)) { + if (!ContextUtils.IsStateComponent(values(this.context.states!)[0])) { + throw new Error('The state component type is wrong'); + } + return values(this.context.states!)[0]; + } + + // or we will use the one specified by user + if (!ContextUtils.IsStateComponent(this.context.states![db!])) { + throw new Error('The state component type is wrong'); + } + return values(this.context.states!)[0]; + } + + /** + * Save the data to the state store + * @param data The data for save operation + * @param db The state store to save the data + * @returns The promise of the save action being executed. + */ + #stateSave(data: object, db?: string): Promise { + return this.daprClient.state.save( + this.getState(db).componentName, + values(data)[0] as KeyValuePairType[] + ); + } + + /** + * Get the data from the state store + * @param data The data for get operation + * @param db The state store to get the data + * @returns The promise of the get action being executed. + */ + #stateGet(data: object, db?: string): Promise { + if (isEmpty(data) || size(data) > 1) { + throw new Error('State get method: invalid key number'); + } + + return this.daprClient.state.get( + this.getState(db).componentName, + values(data)[0] as string + ); + } + + /** + * Get the datas from the state store + * @param data The data for getBulk operation + * @param db The state store to getBulk the data + * @returns The promise of the getBulk action being executed. + */ + #stateGetBulk(data: object, db?: string): Promise { + const [keys, parallelism, metadata] = values(data) as unknown as [ + string[], + number, + string + ]; + return this.daprClient.state.getBulk( + this.getState(db).componentName, + keys, + parallelism, + metadata + ); + } + + /** + * Delete the data from the state store + * @param data The data for delete operation + * @param db The state store to delete the data + * @returns The promise of the delete action being executed. + */ + #stateDelete(data: object, db?: string): Promise { + if (isEmpty(data) || size(data) > 1) { + throw new Error('State get method: invalid key number'); + } + + return this.daprClient.state.delete( + this.getState(db).componentName, + values(data)[0] as string + ); + } + + /** + * Transaction the data from the state store + * @param data The data for transaction operation + * @param db The state store to transaction the data + * @returns The promise of the transaction action being executed. + */ + #stateTransaction(data: object, db?: string): Promise { + const [operations, metadata] = values(data) as unknown as [ + OperationType[], + IRequestMetadata + ]; + return this.daprClient.state.transaction( + this.getState(db).componentName, + operations as OperationType[], + metadata ? (metadata as IRequestMetadata) : null + ); + } + + /** + * query the data from the state store + * @param data The data for query operation + * @param db The state store to query the data + * @returns The promise of the query action being executed. + */ + #stateQuery(data: object, db?: string): Promise { + return this.daprClient.state.query( + this.getState(db).componentName, + values(data)[0] as StateQueryType + ); + } + + /** + * The promise that handle data by state store. + */ + get state(): StateOperations { + return { + save: this.#stateSave.bind(this), + get: this.#stateGet.bind(this), + getBulk: this.#stateGetBulk.bind(this), + delete: this.#stateDelete.bind(this), + transaction: this.#stateTransaction.bind(this), + query: this.#stateQuery.bind(this), + }; + } } diff --git a/test/conformance/.env-cmdrc.js b/test/conformance/.env-cmdrc.js index 4e2d094f7..455b84892 100644 --- a/test/conformance/.env-cmdrc.js +++ b/test/conformance/.env-cmdrc.js @@ -14,6 +14,19 @@ module.exports = { }, }, }, + states: { + // there is a policy, if you don't specify the state component, we will use the first one + // or you need specify the state name, then the context will use the one you specify + // hint : specify the name is the record key, not the component name + redis: { + componentName: 'myredis', + componentType: 'state.redis', + }, + mysql: { + componentName: 'mymysql', + componentType: 'state.mysql', + }, + }, }), }, async: { @@ -29,6 +42,19 @@ module.exports = { componentType: 'bindings.cron', }, }, + states: { + // there is a policy, if you don't specify the state component, we will use the first one + // or you need specify the state name, then the context will use the one you specify + // hint : specify the name is the record key, not the component name + redis: { + componentName: 'myredis', + componentType: 'state.redis', + }, + mysql: { + componentName: 'mymysql', + componentType: 'state.mysql', + }, + }, }), }, }; diff --git a/test/conformance/function.js b/test/conformance/function.js index 08da0f738..c973158b8 100644 --- a/test/conformance/function.js +++ b/test/conformance/function.js @@ -44,12 +44,90 @@ function writeJson(content) { fs.writeFileSync(fileName, json); } -async function tryKnativeAsync(ctx, data) { +async function tryKnativeAsyncBindingAndPubSub(ctx, data) { debug('✅ Function should receive request: %o', data); await ctx.send(data); ctx.res.send(data); } +async function tryKnativeAsyncStateSave(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .save(data) + .then(res => { + debug('✅ Success save: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + +async function tryKnativeAsyncStateGet(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .get(data) + .then(res => { + debug('✅ Success save: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + +async function tryKnativeAsyncStateGetBulk(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .getBulk(data) + .then(res => { + debug('✅ Success getBulk: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + +async function tryKnativeAsyncStateDelete(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .delete(data) + .then(res => { + debug('✅ Success delete: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + +async function tryKnativeAsyncStateTransaction(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .transaction(data) + .then(res => { + debug('✅ Success transaction: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + +async function tryKnativeAsyncStateQuery(ctx, data) { + debug('✅ Function should receive request: %o', data); + await ctx.state + .query(data) + .then(res => { + debug('✅ Success query: %o', res); + }) + .catch(err => { + debug('❌ Failure occurred: %o', err); + }); + ctx.res.send(data); +} + function tryAsync(ctx, data) { debug('✅ Function should receive from "%o": %o', ctx.inputs, data); } @@ -58,6 +136,12 @@ module.exports = { writeHttp, writeCloudEvent, writeLegacyEvent, - tryKnativeAsync, + tryKnativeAsyncBindingAndPubSub, + tryKnativeAsyncStateSave, + tryKnativeAsyncStateGet, + tryKnativeAsyncStateGetBulk, + tryKnativeAsyncStateDelete, + tryKnativeAsyncStateTransaction, + tryKnativeAsyncStateQuery, tryAsync, }; diff --git a/test/conformance/package.json b/test/conformance/package.json index 3145dd383..1c43e6cef 100644 --- a/test/conformance/package.json +++ b/test/conformance/package.json @@ -9,10 +9,24 @@ "scripts": { "start": "functions-framework --target=writeHttp", "compile": "cd .. && npm run compile", - "knative:async": "npm run compile && concurrently npm:knative:async:run:* npm:knative:async:test", - "knative:async:run:func": "cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsync", - "knative:async:run:dapr": "dapr run -H 3500 -d ../data/components/http --log-level warn", - "knative:async:test": "wait-on tcp:3500 tcp:8080 && curl -s -d '{\"data\": \"hello\"}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:binding_pubsub": "npm run compile && concurrently npm:knative:async:binding_pubsub:run:* npm:knative:async:binding_pubsub:test", + "knative:async:binding_pubsub:run:func": "cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncBindingAndPubSub", + "knative:async:binding_pubsub:run:dapr": "dapr run -H 3500 -d ../data/components/http --log-level warn", + "knative:async:binding_pubsub:test": "wait-on tcp:3500 tcp:8080 && curl -s -d '{\"data\": \"hello\"}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:docker":"docker run --name myredis --rm -d -p 6379:6379 redis/redis-stack-server:latest", + "knative:async:state:run:dapr":"dapr run -H 3500 -d ../data/components/state --log-level warn", + "knative:async:state:run:func:save": "cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateSave", + "knative:async:state:run:test:save": "wait-on tcp:3500 tcp:8080 && curl -s -d '{\"dataObjects\": [{\"key\": \"1\",\"value\": {\"person\": {\"org\": \"Dev Ops\",\"id\": 1036},\"city\": \"Seattle\",\"state\": \"WA\"}},{\"key\": \"2\",\"value\": {\"person\": {\"org\": \"Hardware\",\"id\": 1028},\"city\": \"Portland\",\"state\": \"OR\"}}]}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:func:get": "cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateGet", + "knative:async:state:run:test:get":"wait-on tcp:3500 tcp:8080 && curl -s -d '{\"key\": \"1\"}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:func:getBulk":"cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateGetBulk", + "knative:async:state:run:test:getBulk":"wait-on tcp:3500 tcp:8080 && curl -s -d '{\"keys\": [\"1\", \"2\"], \"parallelism\": 10}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:func:delete":"cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateDelete", + "knative:async:state:run:test:delete":"wait-on tcp:3500 tcp:8080 && curl -s -d '{\"key\": \"1\"}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:func:transaction":"cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateTransaction", + "knative:async:state:run:test:transaction":"wait-on tcp:3500 tcp:8080 && curl -s -d '{\"operations\": [{\"operation\": \"delete\", \"request\": {\"key\": \"2\"}}, {\"operation\": \"upsert\", \"request\": {\"key\": \"1\", \"value\": {\"person\": {\"org\": \"Dev Ops\", \"id\": 1036}, \"city\": \"Seattle\", \"state\": \"WA\"}}}]}' -H 'Content-Type: application/json' localhost:8080", + "knative:async:state:run:func:query":"cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e knative functions-framework --signature-type=openfunction --target=tryKnativeAsyncStateQuery", + "knative:async:state:run:test:query":"wait-on tcp:3500 tcp:8080 && curl -s -d '{\"query\": {\"filter\": {\"EQ\": {\"state\": \"CA\"}}, \"sort\": [{\"key\": \"person.id\", \"order\": \"DESC\"}], \"page\": {\"limit\": 1}}}' -H 'Content-Type: application/json' localhost:8080", "async": "npm run compile && concurrently npm:async:run:*", "async:run:func": "cross-env DEBUG=test:*,common:*,ofn:* env-cmd -e async functions-framework --target=tryAsync", "async:run:dapr": "dapr run -H 3500 -p 8080 -d ../data/components/cron --log-level info" diff --git a/test/data/components/state/state.yaml b/test/data/components/state/state.yaml new file mode 100644 index 000000000..b3a3b1481 --- /dev/null +++ b/test/data/components/state/state.yaml @@ -0,0 +1,27 @@ +apiVersion: dapr.io/v1alpha1 +kind: Component +metadata: + name: myredis + namespace: default +spec: + type: state.redis + version: v1 + metadata: + - name: redisHost + value: localhost:6379 + - name: redisPassword + value: '' + - name: queryIndexes + value: + [ + { + name: 'orgIndx', + indexes: + [ + {key: 'person.org', type: 'TEXT'}, + {key: 'person.id', type: 'NUMERIC'}, + {key: 'state', type: 'TEXT'}, + {key: 'city', type: 'TEXT'}, + ], + }, + ] \ No newline at end of file diff --git a/test/data/mock/context.ts b/test/data/mock/context.ts index 1f934a57b..9334e360e 100644 --- a/test/data/mock/context.ts +++ b/test/data/mock/context.ts @@ -23,6 +23,19 @@ export const KnativeBase: OpenFunctionContext = { }, }, }, + states: { + // there is a policy, if you don't specify the state component, we will use the first one + // or you need specify the state name, then the context will use the one you specify + // hint : specify the name is the record key, not the component name + redis: { + componentName: 'myredis', + componentType: 'state.redis', + }, + mysql: { + componentName: 'mymysql', + componentType: 'state.mysql', + }, + }, }; export const AsyncBase: OpenFunctionContext = { diff --git a/test/data/mock/payload.ts b/test/data/mock/payload.ts index 57bca547a..3efb284a4 100644 --- a/test/data/mock/payload.ts +++ b/test/data/mock/payload.ts @@ -1,8 +1,37 @@ import {CloudEvent} from '../../../src'; +import {KeyValuePairType} from '@dapr/dapr/types/KeyValuePair.type'; +import {OperationType} from '@dapr/dapr/types/Operation.type'; +import {IRequestMetadata} from '@dapr/dapr/types/RequestMetadata.type'; +import {StateQueryType} from '@dapr/dapr/types/state/StateQuery.type'; export interface IPayload { RAW: object; CE?: CloudEvent; + State?: IStateStore; +} + +interface IStateStore { + Save: { + dataObjects: KeyValuePairType[]; + }; + Get: { + key: string; + }; + GetBulk: { + keys: string[]; + parallelism?: number; + metadata?: string[]; + }; + Delete: { + key: string; + }; + Transaction: { + operations?: OperationType[]; + metadata?: IRequestMetadata | null; + }; + Query: { + query: StateQueryType; + }; } export const Plain: IPayload = {RAW: {some: 'payload'}}; @@ -17,3 +46,82 @@ Plain.CE = { datacontenttype: 'application/json', data: Plain.RAW, }; + +Plain.State = { + Save: { + dataObjects: [ + { + key: '1', + value: { + person: { + org: 'Dev Ops', + id: 1036, + }, + city: 'Seattle', + state: 'WA', + }, + }, + { + key: '2', + value: { + person: { + org: 'Hardware', + id: 1028, + }, + city: 'Portland', + state: 'OR', + }, + }, + ], + }, + Get: { + key: '1', + }, + GetBulk: { + keys: ['1', '2'], + parallelism: 10, + }, + Delete: { + key: '1', + }, + Transaction: { + operations: [ + { + operation: 'delete', + request: { + key: '2', + }, + }, + { + operation: 'upsert', + request: { + key: '1', + value: { + person: { + org: 'Dev Ops', + id: 1036, + }, + city: 'Seattle', + state: 'WA', + }, + }, + }, + ], + }, + Query: { + query: { + filter: { + EQ: {state: 'CA'}, + }, + sort: [ + { + key: 'person.id', + order: 'DESC', + }, + ], + page: { + limit: 2, + }, + }, + }, +}; diff --git a/test/integration/http_statestore.ts b/test/integration/http_statestore.ts new file mode 100644 index 000000000..6550935ac --- /dev/null +++ b/test/integration/http_statestore.ts @@ -0,0 +1,184 @@ +import {deepStrictEqual} from 'assert'; + +import * as sinon from 'sinon'; +import * as supertest from 'supertest'; +import * as shell from 'shelljs'; +import {cloneDeep, map, omit} from 'lodash'; + +import {OpenFunctionRuntime} from '../../src/functions'; +import {FUNCTION_STATUS_HEADER_FIELD} from '../../src/types'; +import {getServer} from '../../src/server'; +import {StateOperations} from '../../src/openfunction/runtime'; + +import {Context, Payload} from '../data/mock'; +import {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; + +const TEST_CONTEXT = { + ...Context.KnativeBase, +}; + +const TEST_STATESTORE_SAVE = Payload.Plain.State!.Save; +const TEST_STATESTORE_GET = Payload.Plain.State!.Get; +const TEST_STATESTORE_BULK = Payload.Plain.State!.GetBulk; +const TEST_STATESTORE_DELETE = Payload.Plain.State!.Delete; +const TEST_STATESTORE_TRANSACTION = Payload.Plain.State!.Transaction; +const TEST_STATESTORE_QUERY = Payload.Plain.State!.Query; + +type StateOperation = keyof StateOperations; + +describe('OpenFunction - HTTP StateStore', () => { + const APPID = 'http_statestore'; + + before(() => { + if (shell.exec('dapr', {silent: true}).code !== 0) + throw new Error('Please ensure "dapr" is installed'); + + if (shell.exec('docker', {silent: true}).code !== 0) + throw new Error('Please ensure "docker" is installed'); + + // Try to start up redis docker container + shell.exec( + 'docker run --name myredis --rm -d -p 6379:6379 redis/redis-stack-server:latest', + { + silent: true, + } + ); + + // Try to run Dapr sidecar on port 3500 with components for testing + shell.exec( + `dapr run -H 3500 -G 50001 -d ./test/data/components/state -a ${APPID}`, + {silent: true, async: true} + ); + }); + + after(() => { + // Stop redis container + shell.exec('docker stop myredis', {silent: true}); + // Stop dapr sidecar process + shell.exec(`dapr stop ${APPID}`, {silent: true}); + }); + + beforeEach(() => { + // Prevent log spew from the PubSub emulator request. + sinon.stub(console, 'error'); + }); + afterEach(() => { + (console.error as sinon.SinonSpy).restore(); + }); + + const testData = [ + { + name: 'Save data', + tosend: TEST_STATESTORE_SAVE, + operation: 'save', + expect: undefined, + }, + { + name: 'Get data', + operation: 'get', + tosend: TEST_STATESTORE_GET, + expect: { + city: 'Seattle', + person: { + id: 1036, + org: 'Dev Ops', + }, + state: 'WA', + }, + }, + { + name: 'GetBulk data', + operation: 'getBulk', + tosend: TEST_STATESTORE_BULK, + expect: [ + { + data: { + city: 'Seattle', + person: { + id: 1036, + org: 'Dev Ops', + }, + state: 'WA', + }, + key: '1', + }, + { + data: { + city: 'Portland', + person: { + id: 1028, + org: 'Hardware', + }, + state: 'OR', + }, + key: '2', + }, + ], + }, + { + name: 'Delete data', + operation: 'delete', + tosend: TEST_STATESTORE_DELETE, + expect: undefined, + }, + { + name: 'Transcation data', + operation: 'transaction', + tosend: TEST_STATESTORE_TRANSACTION, + expect: undefined, + }, + { + name: 'Query data', + operation: 'query', + tosend: TEST_STATESTORE_QUERY, + // expect: undefined, + }, + ]; + + for (const test of testData) { + it(test.name, async () => { + const context = cloneDeep(TEST_CONTEXT); + // test the ouput of the state sotre + const server = getServer( + async (ctx: OpenFunctionRuntime, data: {}) => { + if (!test.operation) throw new Error('I crashed'); + + await ctx.state[test.operation as StateOperation](data) + .then(res => { + if (test.operation === 'getBulk') { + res = map(res as KeyValueType[], obj => omit(obj, 'etag')); + } + // todo: query still have some problems + if (test.operation === 'query') { + console.log(res); + } + deepStrictEqual(res, test.expect); + }) + .catch(err => { + console.log(err); + }); + // FIXME: This makes server respond right away, even before post hooks + ctx.res?.send(data); + }, + 'openfunction', + context + ); + + await supertest(server) + .post('/') + .send(test.tosend) + .expect(test.operation ? 200 : 500) + // Assert HTTP response first + .then(res => { + if (!test.operation) { + deepStrictEqual( + res.headers[FUNCTION_STATUS_HEADER_FIELD.toLowerCase()], + 'error' + ); + } else { + deepStrictEqual(res.body, test.tosend); + } + }); + }); + } +});