From 551e4ac10053148706fe56dac622dd7ec5beab73 Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Thu, 6 Jul 2023 18:46:12 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=F0=9F=8C=88=20style:=20update=20import=20s?= =?UTF-8?q?tyle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- src/main.ts | 2 +- src/openfunction/async_server.ts | 2 +- test/integration/async_server.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.ts b/src/main.ts index 1bf9c6411..91e77238c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -20,7 +20,7 @@ import * as process from 'process'; import {createHttpTerminator} from 'http-terminator'; -import getAysncServer from './openfunction/async_server'; +import {getAysncServer} from './openfunction/async_server'; import {ContextUtils} from './openfunction/context'; import {getUserFunction, getFunctionPlugins, getBuiltinPlugins} from './loader'; diff --git a/src/openfunction/async_server.ts b/src/openfunction/async_server.ts index 9e80664a3..faf11b904 100644 --- a/src/openfunction/async_server.ts +++ b/src/openfunction/async_server.ts @@ -15,7 +15,7 @@ export type AsyncFunctionServer = DaprServer; * @param context Context of user's function. * @return HTTP server. */ -export default function ( +export function getAysncServer( userFunction: OpenFunction, context: OpenFunctionContext ): AsyncFunctionServer { diff --git a/test/integration/async_server.ts b/test/integration/async_server.ts index c9254adc1..e06c34619 100644 --- a/test/integration/async_server.ts +++ b/test/integration/async_server.ts @@ -5,7 +5,7 @@ import {fill, get, isEmpty} from 'lodash'; import * as shell from 'shelljs'; import * as MQTT from 'aedes'; -import getAysncServer from '../../src/openfunction/async_server'; +import {getAysncServer} from '../../src/openfunction/async_server'; import {getFunctionPlugins} from '../../src/loader'; import {Context, Payload} from '../data/mock'; From dfd79a2d0b81dd4a25bbca38ec4ef236e4956e72 Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Sat, 8 Jul 2023 21:56:46 +0800 Subject: [PATCH 2/7] =?UTF-8?q?=E2=9C=A8=20feat:=20support=20the=20state?= =?UTF-8?q?=20store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- docs/generated/api.json | 306 +++++++++++++++++++++ docs/generated/api.md | 20 +- src/openfunction/context.ts | 35 +++ src/openfunction/runtime.ts | 230 ++++++++++++++++ test/data/components/state/statestore.yaml | 27 ++ test/data/mock/context.ts | 26 ++ test/data/mock/index.ts | 1 + test/data/mock/statestore.ts | 124 +++++++++ test/integration/http_statestore.ts | 219 +++++++++++++++ 9 files changed, 987 insertions(+), 1 deletion(-) create mode 100644 test/data/components/state/statestore.yaml create mode 100644 test/data/mock/statestore.ts create mode 100644 test/integration/http_statestore.ts diff --git a/docs/generated/api.json b/docs/generated/api.json index 0bf0410a0..5732a5895 100644 --- a/docs/generated/api.json +++ b/docs/generated/api.json @@ -521,6 +521,119 @@ ], "extendsTokenRanges": [] }, + { + "kind": "Interface", + "canonicalReference": "@openfunction/functions-framework!ComponentSpec:interface", + "docComment": "/**\n * The specification of the component\n *\n * @public\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export interface ComponentSpec " + } + ], + "fileUrlPath": "src/openfunction/context.ts", + "releaseTag": "Public", + "name": "ComponentSpec", + "preserveMemberOrder": false, + "members": [ + { + "kind": "PropertySignature", + "canonicalReference": "@openfunction/functions-framework!ComponentSpec#metadata:member", + "docComment": "/**\n * Optional metadata as hash map for the component.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "metadata?: " + }, + { + "kind": "Reference", + "text": "Record", + "canonicalReference": "!Record:type" + }, + { + "kind": "Content", + "text": "" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": true, + "releaseTag": "Public", + "name": "metadata", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 3 + } + }, + { + "kind": "PropertySignature", + "canonicalReference": "@openfunction/functions-framework!ComponentSpec#type:member", + "docComment": "/**\n * The name of the state store.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "type: " + }, + { + "kind": "Content", + "text": "`${" + }, + { + "kind": "Reference", + "text": "ComponentType", + "canonicalReference": "@openfunction/functions-framework!ComponentType:enum" + }, + { + "kind": "Content", + "text": "}.${string}`" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "type", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 4 + } + }, + { + "kind": "PropertySignature", + "canonicalReference": "@openfunction/functions-framework!ComponentSpec#version:member", + "docComment": "/**\n * The version of the component\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "version: " + }, + { + "kind": "Content", + "text": "string" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": false, + "isOptional": false, + "releaseTag": "Public", + "name": "version", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + } + } + ], + "extendsTokenRanges": [] + }, { "kind": "Enum", "canonicalReference": "@openfunction/functions-framework!ComponentType:enum", @@ -577,6 +690,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 +960,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": "ComponentSpec", + "canonicalReference": "@openfunction/functions-framework!ComponentSpec: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 +2233,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 +2858,89 @@ "isStatic": false, "isProtected": false }, + { + "kind": "Property", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionRuntime#state:member", + "docComment": "/**\n * The state store and its operations\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "abstract get state(): " + }, + { + "kind": "Content", + "text": "{\n save: (data: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n get: (data: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n getBulk: (data: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n delete: (data: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n transaction: (data: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n query: (query: object, db?: string) => " + }, + { + "kind": "Reference", + "text": "Promise", + "canonicalReference": "!Promise:interface" + }, + { + "kind": "Content", + "text": ";\n }" + }, + { + "kind": "Content", + "text": ";" + } + ], + "isReadonly": true, + "isOptional": false, + "releaseTag": "Public", + "name": "state", + "propertyTypeTokenRange": { + "startIndex": 1, + "endIndex": 14 + }, + "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..0d7703d59 100644 --- a/docs/generated/api.md +++ b/docs/generated/api.md @@ -41,10 +41,18 @@ export interface CloudFunctionsContext { timestamp?: string; } +// @public +export interface ComponentSpec { + metadata?: Record; + type: `${ComponentType}.${string}`; + version: string; +} + // @public export enum ComponentType { Binding = "bindings", - PubSub = "pubsub" + PubSub = "pubsub", + State = "state" } // @public @@ -56,6 +64,7 @@ export class ContextUtils { static IsBindingComponent(component: OpenFunctionComponent): boolean; static IsKnativeRuntime(context: OpenFunctionContext): boolean; static IsPubSubComponent(component: OpenFunctionComponent): boolean; + static IsStateComponent(component: ComponentSpec): boolean; } // @public @@ -136,6 +145,7 @@ export interface OpenFunctionContext { postPlugins?: string[]; prePlugins?: string[]; runtime: `${RuntimeType}` | `${Capitalize}` | `${Uppercase}`; + states?: Record; version: string; } @@ -156,6 +166,14 @@ export abstract class OpenFunctionRuntime { HTTP: string; GRPC: string; }; + abstract get state(): { + 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; + }; // 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..38393b5c8 100644 --- a/src/openfunction/context.ts +++ b/src/openfunction/context.ts @@ -42,6 +42,10 @@ export interface OpenFunctionContext { * Optional trace plugin config. */ pluginsTracing?: TraceConfig; + /** + * Optional state store config; + */ + states?: Record; } /** @@ -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: ComponentSpec): boolean { + return component?.type.split('.')[0] === ComponentType.State; + } } /** @@ -196,3 +212,22 @@ export enum TraceProviderType { */ OpenTelemetry = 'opentelemetry', } + +/** + * The specification of the component + * @public + */ +export interface ComponentSpec { + /** + * The name of the state store. + */ + type: `${ComponentType}.${string}`; + /** + * The version of the component + */ + version: string; + /** + * Optional metadata as hash map for the component. + */ + metadata?: Record; +} diff --git a/src/openfunction/runtime.ts b/src/openfunction/runtime.ts index b990c2ecb..ec4914dc2 100644 --- a/src/openfunction/runtime.ts +++ b/src/openfunction/runtime.ts @@ -2,7 +2,12 @@ import {env} from 'process'; import {chain, get, has, extend, isPlainObject} from 'lodash'; import {Request, Response} from 'express'; + import {DaprClient, CommunicationProtocolEnum} from '@dapr/dapr'; +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'; import {OpenFunction} from '../functions'; @@ -10,6 +15,7 @@ import { OpenFunctionComponent, OpenFunctionContext, ContextUtils, + ComponentSpec, } from './context'; import {Plugin, PluginStore} from './plugin'; @@ -184,6 +190,18 @@ export abstract class OpenFunctionRuntime { * The promise that send data to certain ouput. */ abstract send(data: object, output?: string): Promise; + + /** + * The state store and its operations + */ + abstract get state(): { + 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 +261,216 @@ class DaprRuntime extends OpenFunctionRuntime { return Promise.allSettled(actions); } + + /** + * 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. + */ + #save(data: object, db?: string): Promise { + if (!this.context.states) { + return Promise.resolve([]); + } + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + return this.daprClient.state.save( + storeName, + data as KeyValuePairType[] + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * 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. + */ + #get(data: object, db?: string): Promise { + if (!this.context.states) { + return Promise.resolve([]); + } + + // check the data whether legal + const data_length = Object.values(data).length; + if (data_length > 1 || data_length <= 0) { + throw new Error('State get method: invalid keys number'); + } + + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + return this.daprClient.state.get( + storeName, + Object.values(data)[0] as string + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * 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. + */ + #getBulk(data: object, db?: string) { + if (!this.context.states) { + return Promise.resolve([]); + } + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + const [keys, parallelism, metadata] = Object.values(data) as [ + string[], + number, + string + ]; + return this.daprClient.state.getBulk( + storeName, + keys, + parallelism, + metadata + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * 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. + */ + #delete(data: object, db?: string): Promise { + if (!this.context.states) { + return Promise.resolve([]); + } + + // check the data whether legal + const data_length = Object.values(data).length; + if (data_length > 1 || data_length <= 0) { + throw new Error('State get method: invalid keys number'); + } + + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + return this.daprClient.state.delete( + storeName, + Object.values(data)[0] as string + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * 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. + * Note that this depends on the state store component that supports multi-item transactions. + * List of state stores that support transactions: + * More information: https://docs.dapr.io/reference/components-reference/supported-state-stores/ + */ + #transaction(data: object, db?: string): Promise { + if (!this.context.states) { + return Promise.resolve([]); + } + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + const [operations, metadata] = Object.values(data) as [ + OperationType[], + IRequestMetadata + ]; + return this.daprClient.state.transaction( + storeName, + operations as OperationType[], + metadata ? (metadata as IRequestMetadata) : null + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * 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. + */ + #query(data: object, db?: string): Promise { + if (!this.context.states) { + return Promise.resolve([]); + } + const states = this.context.states; + const actions = Object.keys(states) + .filter(v => !db || v === db) + .map((storeName: string) => { + const component: ComponentSpec = states[storeName]; + if (ContextUtils.IsStateComponent(component)) { + return this.daprClient.state.query( + storeName, + Object.values(data)[0] as StateQueryType + ); + } + return Promise.resolve(undefined); + }) + .values(); + return Promise.allSettled(actions); + } + + /** + * Use getter to add a layer of objects + */ + get state(): { + 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: (data: object, db?: string) => Promise; + } { + return { + save: this.#save.bind(this), + get: this.#get.bind(this), + getBulk: this.#getBulk.bind(this), + delete: this.#delete.bind(this), + transaction: this.#transaction.bind(this), + query: this.#query.bind(this), + }; + } } diff --git a/test/data/components/state/statestore.yaml b/test/data/components/state/statestore.yaml new file mode 100644 index 000000000..c8e05f095 --- /dev/null +++ b/test/data/components/state/statestore.yaml @@ -0,0 +1,27 @@ +apiVersion: dapr.io/v1alpha1 +kind: Component +metadata: + name: redis + 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..e91a6e560 100644 --- a/test/data/mock/context.ts +++ b/test/data/mock/context.ts @@ -1,6 +1,7 @@ import { OpenFunctionContext, TraceConfig, + ComponentSpec, } from '../../../src/openfunction/context'; export const KnativeBase: OpenFunctionContext = { @@ -86,3 +87,28 @@ export const TracerPluginBase: TraceConfig = { value: 'value1', }, }; + +export const StateStoreBase: Record = { + redis: { + type: 'state.redis', + version: 'v1', + metadata: { + redisHost: 'localhost:6379', + redisPassword: '', + }, + }, + // mysql: { + // type: 'state.mysql', + // version: 'v1', + // metadata: { + // connectionString: '', + // schemaName: '', + // tableName: '', + // timeoutInSeconds: '30', + // // Required if pemContents not provided. Path to pem file. + // pemPath: '', + // // Required if pemPath not provided. Pem value + // pemContents: '', + // }, + // }, +}; diff --git a/test/data/mock/index.ts b/test/data/mock/index.ts index eba4e29ce..b26288a51 100644 --- a/test/data/mock/index.ts +++ b/test/data/mock/index.ts @@ -1,2 +1,3 @@ export * as Context from './context'; export * as Payload from './payload'; +export * as StateStore from './statestore'; diff --git a/test/data/mock/statestore.ts b/test/data/mock/statestore.ts new file mode 100644 index 000000000..bc52238a9 --- /dev/null +++ b/test/data/mock/statestore.ts @@ -0,0 +1,124 @@ +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'; + +/** + * The statestore interface of the data. + * @public + */ +export interface IStateStore { + Save: 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: IStateStore = { + Save: [ + { + key: 'weapon', + value: 'DeathStar', + etag: '1234', // some dbs don't support this + }, + { + key: 'planet', + value: { + name: 'Tatooine', + }, + }, + ], + Get: { + key: 'weapon', + }, + GetBulk: { + keys: ['weapon', 'planet'], + parallelism: 10, + }, + Delete: { + key: 'weapon', + }, + Transaction: { + operations: [ + { + operation: 'delete', + request: { + key: 'planet', + }, + }, + { + operation: 'upsert', + request: { + key: '1', + value: { + person: { + org: 'Dev Ops', + id: 1036, + }, + city: 'Seattle', + state: 'WA', + }, + }, + }, + { + operation: 'upsert', + request: { + key: '5', + value: { + person: { + org: 'Hardware', + id: 1007, + }, + city: 'Los Angeles', + state: 'CA', + }, + }, + }, + { + operation: 'upsert', + request: { + key: '3', + value: { + person: { + org: 'Finance', + id: 1071, + }, + city: 'Sacramento', + state: 'CA', + }, + }, + }, + ], + }, + 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..52e091bf4 --- /dev/null +++ b/test/integration/http_statestore.ts @@ -0,0 +1,219 @@ +import {deepStrictEqual} from 'assert'; + +import * as sinon from 'sinon'; +import * as supertest from 'supertest'; +import * as shell from 'shelljs'; +import {cloneDeep} from 'lodash'; + +import {OpenFunctionRuntime} from '../../src/functions'; +import {FUNCTION_STATUS_HEADER_FIELD} from '../../src/types'; +import {getServer} from '../../src/server'; +import {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; + +import {Context, StateStore} from '../data/mock'; +import {StateStoreBase} from '../data/mock/context'; + +const TEST_CONTEXT = { + ...Context.KnativeBase, + states: StateStoreBase, +}; + +const TEST_STATESTORE_SAVE = StateStore.Plain.Save; +const TEST_STATESTORE_GET = StateStore.Plain.Get; +const TEST_STATESTORE_BULK = StateStore.Plain.GetBulk; +const TEST_STATESTORE_DELETE = StateStore.Plain.Delete; +const TEST_STATESTORE_TRANSACTION = StateStore.Plain.Transaction; +const TEST_STATESTORE_QUERY = StateStore.Plain.Query; + +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 redis --rm -d -p 6379:6379 redis:latest', + 'docker run --name redis --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 redis', {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: 'DeathStar', + }, + { + name: 'GetBulk data', + operation: 'getbulk', + tosend: TEST_STATESTORE_BULK, + expect: [ + { + key: 'weapon', + data: 'DeathStar', + }, + { + key: 'planet', + data: {name: 'Tatooine'}, + }, + ], + }, + { + 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'); + switch (test.operation) { + case 'save': + await ctx.state + .save(data, 'redis') + .then(res => { + deepStrictEqual(Object.values(res)[0].value, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + case 'get': + await ctx.state + .get(data, 'redis') + .then(res => { + deepStrictEqual(Object.values(res)[0].value, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + case 'getbulk': + await ctx.state + .getBulk(data, 'redis') + .then(res => { + const promise_data = Object.values(res)[0] + .value as Array; + const promise_data_remove_etag = promise_data.map(obj => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const {etag, ...rest} = obj; + return rest; + }); + deepStrictEqual(promise_data_remove_etag, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + case 'delete': + await ctx.state + .delete(data, 'redis') + .then(res => { + deepStrictEqual(Object.values(res)[0].value, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + case 'transaction': + await ctx.state + .transaction(data, 'redis') + .then(res => { + deepStrictEqual(Object.values(res)[0].value, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + case 'query': + await ctx.state + .query(data, 'redis') + .then(res => { + console.log(res); + // deepStrictEqual(Object.values(res)[0].value, test.expect); + }) + .catch(err => { + console.log(err); + }); + break; + default: + throw new Error(`Unknown operation: ${test.operation}`); + } + // 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); + } + }); + }); + } +}); From 1c77a7035d3aa28e2d38aec411558ee2ab40d113 Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Mon, 10 Jul 2023 09:31:42 +0800 Subject: [PATCH 3/7] =?UTF-8?q?Revert=20"=F0=9F=8C=88=20style:=20update=20?= =?UTF-8?q?import=20style"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit edfa1f92672533906e5c1fcd416e2e985d2baa24. Signed-off-by: yi-ge-dian --- src/main.ts | 2 +- src/openfunction/async_server.ts | 2 +- test/integration/async_server.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.ts b/src/main.ts index 91e77238c..1bf9c6411 100644 --- a/src/main.ts +++ b/src/main.ts @@ -20,7 +20,7 @@ import * as process from 'process'; import {createHttpTerminator} from 'http-terminator'; -import {getAysncServer} from './openfunction/async_server'; +import getAysncServer from './openfunction/async_server'; import {ContextUtils} from './openfunction/context'; import {getUserFunction, getFunctionPlugins, getBuiltinPlugins} from './loader'; diff --git a/src/openfunction/async_server.ts b/src/openfunction/async_server.ts index faf11b904..9e80664a3 100644 --- a/src/openfunction/async_server.ts +++ b/src/openfunction/async_server.ts @@ -15,7 +15,7 @@ export type AsyncFunctionServer = DaprServer; * @param context Context of user's function. * @return HTTP server. */ -export function getAysncServer( +export default function ( userFunction: OpenFunction, context: OpenFunctionContext ): AsyncFunctionServer { diff --git a/test/integration/async_server.ts b/test/integration/async_server.ts index e06c34619..c9254adc1 100644 --- a/test/integration/async_server.ts +++ b/test/integration/async_server.ts @@ -5,7 +5,7 @@ import {fill, get, isEmpty} from 'lodash'; import * as shell from 'shelljs'; import * as MQTT from 'aedes'; -import {getAysncServer} from '../../src/openfunction/async_server'; +import getAysncServer from '../../src/openfunction/async_server'; import {getFunctionPlugins} from '../../src/loader'; import {Context, Payload} from '../data/mock'; From 04477e9f0a283ad845c90f27184597df7afcc37d Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Mon, 10 Jul 2023 21:35:21 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=F0=9F=A6=84=20refactor:=20refactor=20the?= =?UTF-8?q?=20code=20for=20state=20store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- src/openfunction/context.ts | 31 +-- src/openfunction/runtime.ts | 246 +++++++----------- .../state/{statestore.yaml => state.yaml} | 2 +- test/data/mock/context.ts | 39 +-- test/integration/http_statestore.ts | 20 +- 5 files changed, 119 insertions(+), 219 deletions(-) rename test/data/components/state/{statestore.yaml => state.yaml} (97%) diff --git a/src/openfunction/context.ts b/src/openfunction/context.ts index 38393b5c8..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. */ @@ -42,10 +46,6 @@ export interface OpenFunctionContext { * Optional trace plugin config. */ pluginsTracing?: TraceConfig; - /** - * Optional state store config; - */ - states?: Record; } /** @@ -152,8 +152,8 @@ export class ContextUtils { * @param component - The component to check. * @returns A boolean value. */ - static IsStateComponent(component: ComponentSpec): boolean { - return component?.type.split('.')[0] === ComponentType.State; + static IsStateComponent(component: OpenFunctionComponent): boolean { + return component?.componentType.split('.')[0] === ComponentType.State; } } @@ -212,22 +212,3 @@ export enum TraceProviderType { */ OpenTelemetry = 'opentelemetry', } - -/** - * The specification of the component - * @public - */ -export interface ComponentSpec { - /** - * The name of the state store. - */ - type: `${ComponentType}.${string}`; - /** - * The version of the component - */ - version: string; - /** - * Optional metadata as hash map for the component. - */ - metadata?: Record; -} diff --git a/src/openfunction/runtime.ts b/src/openfunction/runtime.ts index ec4914dc2..a693b5b86 100644 --- a/src/openfunction/runtime.ts +++ b/src/openfunction/runtime.ts @@ -5,9 +5,11 @@ 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'; @@ -15,7 +17,6 @@ import { OpenFunctionComponent, OpenFunctionContext, ContextUtils, - ComponentSpec, } from './context'; import {Plugin, PluginStore} from './plugin'; @@ -192,15 +193,15 @@ export abstract class OpenFunctionRuntime { abstract send(data: object, output?: string): Promise; /** - * The state store and its operations + * The promise that handle data by state store. */ abstract get state(): { - 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; + 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; }; } @@ -262,31 +263,43 @@ 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 (!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 (!db) { + if (!ContextUtils.IsStateComponent(this.context.states![0])) { + throw new Error('The state component type is wrong'); + } + return Object.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 this.context.states[db]; + } + /** * 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. */ - #save(data: object, db?: string): Promise { - if (!this.context.states) { - return Promise.resolve([]); - } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - return this.daprClient.state.save( - storeName, - data as KeyValuePairType[] - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + #stateSave(data: object, db?: string): Promise { + return this.daprClient.state.save( + this.getState(db).componentName, + data as KeyValuePairType[] + ); } /** @@ -295,32 +308,16 @@ class DaprRuntime extends OpenFunctionRuntime { * @param db The state store to get the data * @returns The promise of the get action being executed. */ - #get(data: object, db?: string): Promise { - if (!this.context.states) { - return Promise.resolve([]); - } - - // check the data whether legal + #stateGet(data: object, db?: string): Promise { const data_length = Object.values(data).length; if (data_length > 1 || data_length <= 0) { - throw new Error('State get method: invalid keys number'); + throw new Error('State get method: invalid key number'); } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - return this.daprClient.state.get( - storeName, - Object.values(data)[0] as string - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + return this.daprClient.state.get( + this.getState(db).componentName, + Object.values(data)[0] as string + ); } /** @@ -329,32 +326,18 @@ class DaprRuntime extends OpenFunctionRuntime { * @param db The state store to getBulk the data * @returns The promise of the getBulk action being executed. */ - #getBulk(data: object, db?: string) { - if (!this.context.states) { - return Promise.resolve([]); - } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - const [keys, parallelism, metadata] = Object.values(data) as [ - string[], - number, - string - ]; - return this.daprClient.state.getBulk( - storeName, - keys, - parallelism, - metadata - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + #stateGetBulk(data: object, db?: string): Promise { + const [keys, parallelism, metadata] = Object.values(data) as [ + string[], + number, + string + ]; + return this.daprClient.state.getBulk( + this.getState(db).componentName, + keys, + parallelism, + metadata + ); } /** @@ -363,32 +346,16 @@ class DaprRuntime extends OpenFunctionRuntime { * @param db The state store to delete the data * @returns The promise of the delete action being executed. */ - #delete(data: object, db?: string): Promise { - if (!this.context.states) { - return Promise.resolve([]); - } - - // check the data whether legal + #stateDelete(data: object, db?: string) { const data_length = Object.values(data).length; if (data_length > 1 || data_length <= 0) { throw new Error('State get method: invalid keys number'); } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - return this.daprClient.state.delete( - storeName, - Object.values(data)[0] as string - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + return this.daprClient.state.delete( + this.getState(db).componentName, + Object.values(data)[0] as string + ); } /** @@ -396,34 +363,17 @@ class DaprRuntime extends OpenFunctionRuntime { * @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. - * Note that this depends on the state store component that supports multi-item transactions. - * List of state stores that support transactions: - * More information: https://docs.dapr.io/reference/components-reference/supported-state-stores/ */ - #transaction(data: object, db?: string): Promise { - if (!this.context.states) { - return Promise.resolve([]); - } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - const [operations, metadata] = Object.values(data) as [ - OperationType[], - IRequestMetadata - ]; - return this.daprClient.state.transaction( - storeName, - operations as OperationType[], - metadata ? (metadata as IRequestMetadata) : null - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + #stateTransaction(data: object, db?: string): Promise { + const [operations, metadata] = Object.values(data) as [ + OperationType[], + IRequestMetadata + ]; + return this.daprClient.state.transaction( + this.getState(db).componentName, + operations as OperationType[], + metadata ? (metadata as IRequestMetadata) : null + ); } /** @@ -432,45 +382,31 @@ class DaprRuntime extends OpenFunctionRuntime { * @param db The state store to query the data * @returns The promise of the query action being executed. */ - #query(data: object, db?: string): Promise { - if (!this.context.states) { - return Promise.resolve([]); - } - const states = this.context.states; - const actions = Object.keys(states) - .filter(v => !db || v === db) - .map((storeName: string) => { - const component: ComponentSpec = states[storeName]; - if (ContextUtils.IsStateComponent(component)) { - return this.daprClient.state.query( - storeName, - Object.values(data)[0] as StateQueryType - ); - } - return Promise.resolve(undefined); - }) - .values(); - return Promise.allSettled(actions); + #stateQuery(data: object, db?: string): Promise { + return this.daprClient.state.query( + this.getState(db).componentName, + Object.values(data)[0] as StateQueryType + ); } /** - * Use getter to add a layer of objects + * The promise that handle data by state store. */ get state(): { - 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: (data: object, db?: string) => Promise; + 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; } { return { - save: this.#save.bind(this), - get: this.#get.bind(this), - getBulk: this.#getBulk.bind(this), - delete: this.#delete.bind(this), - transaction: this.#transaction.bind(this), - query: this.#query.bind(this), + 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/data/components/state/statestore.yaml b/test/data/components/state/state.yaml similarity index 97% rename from test/data/components/state/statestore.yaml rename to test/data/components/state/state.yaml index c8e05f095..b3a3b1481 100644 --- a/test/data/components/state/statestore.yaml +++ b/test/data/components/state/state.yaml @@ -1,7 +1,7 @@ apiVersion: dapr.io/v1alpha1 kind: Component metadata: - name: redis + name: myredis namespace: default spec: type: state.redis diff --git a/test/data/mock/context.ts b/test/data/mock/context.ts index e91a6e560..9334e360e 100644 --- a/test/data/mock/context.ts +++ b/test/data/mock/context.ts @@ -1,7 +1,6 @@ import { OpenFunctionContext, TraceConfig, - ComponentSpec, } from '../../../src/openfunction/context'; export const KnativeBase: OpenFunctionContext = { @@ -24,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 = { @@ -87,28 +99,3 @@ export const TracerPluginBase: TraceConfig = { value: 'value1', }, }; - -export const StateStoreBase: Record = { - redis: { - type: 'state.redis', - version: 'v1', - metadata: { - redisHost: 'localhost:6379', - redisPassword: '', - }, - }, - // mysql: { - // type: 'state.mysql', - // version: 'v1', - // metadata: { - // connectionString: '', - // schemaName: '', - // tableName: '
', - // timeoutInSeconds: '30', - // // Required if pemContents not provided. Path to pem file. - // pemPath: '', - // // Required if pemPath not provided. Pem value - // pemContents: '', - // }, - // }, -}; diff --git a/test/integration/http_statestore.ts b/test/integration/http_statestore.ts index 52e091bf4..b31d5a6f8 100644 --- a/test/integration/http_statestore.ts +++ b/test/integration/http_statestore.ts @@ -11,11 +11,9 @@ import {getServer} from '../../src/server'; import {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; import {Context, StateStore} from '../data/mock'; -import {StateStoreBase} from '../data/mock/context'; const TEST_CONTEXT = { ...Context.KnativeBase, - states: StateStoreBase, }; const TEST_STATESTORE_SAVE = StateStore.Plain.Save; @@ -37,8 +35,8 @@ describe('OpenFunction - HTTP StateStore', () => { // Try to start up redis docker container shell.exec( - // 'docker run --name redis --rm -d -p 6379:6379 redis:latest', - 'docker run --name redis --rm -d -p 6379:6379 redis/redis-stack-server:latest', + // 'docker run --name myredis --rm -d -p 6379:6379 redis:latest', + 'docker run --name myredis --rm -d -p 6379:6379 redis/redis-stack-server:latest', { silent: true, } @@ -53,7 +51,7 @@ describe('OpenFunction - HTTP StateStore', () => { after(() => { // Stop redis container - shell.exec('docker stop redis', {silent: true}); + shell.exec('docker stop myredis', {silent: true}); // Stop dapr sidecar process shell.exec(`dapr stop ${APPID}`, {silent: true}); }); @@ -125,7 +123,7 @@ describe('OpenFunction - HTTP StateStore', () => { await ctx.state .save(data, 'redis') .then(res => { - deepStrictEqual(Object.values(res)[0].value, test.expect); + deepStrictEqual(res, test.expect); }) .catch(err => { console.log(err); @@ -135,7 +133,7 @@ describe('OpenFunction - HTTP StateStore', () => { await ctx.state .get(data, 'redis') .then(res => { - deepStrictEqual(Object.values(res)[0].value, test.expect); + deepStrictEqual(res, test.expect); }) .catch(err => { console.log(err); @@ -145,9 +143,7 @@ describe('OpenFunction - HTTP StateStore', () => { await ctx.state .getBulk(data, 'redis') .then(res => { - const promise_data = Object.values(res)[0] - .value as Array; - const promise_data_remove_etag = promise_data.map(obj => { + const promise_data_remove_etag = res.map(obj => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const {etag, ...rest} = obj; return rest; @@ -162,7 +158,7 @@ describe('OpenFunction - HTTP StateStore', () => { await ctx.state .delete(data, 'redis') .then(res => { - deepStrictEqual(Object.values(res)[0].value, test.expect); + deepStrictEqual(res, test.expect); }) .catch(err => { console.log(err); @@ -172,7 +168,7 @@ describe('OpenFunction - HTTP StateStore', () => { await ctx.state .transaction(data, 'redis') .then(res => { - deepStrictEqual(Object.values(res)[0].value, test.expect); + deepStrictEqual(res, test.expect); }) .catch(err => { console.log(err); From f622fb419c776db610457e02f37bcf62167f6f23 Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Mon, 10 Jul 2023 21:37:46 +0800 Subject: [PATCH 5/7] =?UTF-8?q?=F0=9F=93=83=20docs:=20generate=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- docs/generated/api.json | 164 ++++++++++------------------------------ docs/generated/api.md | 25 +++--- 2 files changed, 49 insertions(+), 140 deletions(-) diff --git a/docs/generated/api.json b/docs/generated/api.json index 5732a5895..f3a690c46 100644 --- a/docs/generated/api.json +++ b/docs/generated/api.json @@ -521,119 +521,6 @@ ], "extendsTokenRanges": [] }, - { - "kind": "Interface", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec:interface", - "docComment": "/**\n * The specification of the component\n *\n * @public\n */\n", - "excerptTokens": [ - { - "kind": "Content", - "text": "export interface ComponentSpec " - } - ], - "fileUrlPath": "src/openfunction/context.ts", - "releaseTag": "Public", - "name": "ComponentSpec", - "preserveMemberOrder": false, - "members": [ - { - "kind": "PropertySignature", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec#metadata:member", - "docComment": "/**\n * Optional metadata as hash map for the component.\n */\n", - "excerptTokens": [ - { - "kind": "Content", - "text": "metadata?: " - }, - { - "kind": "Reference", - "text": "Record", - "canonicalReference": "!Record:type" - }, - { - "kind": "Content", - "text": "" - }, - { - "kind": "Content", - "text": ";" - } - ], - "isReadonly": false, - "isOptional": true, - "releaseTag": "Public", - "name": "metadata", - "propertyTypeTokenRange": { - "startIndex": 1, - "endIndex": 3 - } - }, - { - "kind": "PropertySignature", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec#type:member", - "docComment": "/**\n * The name of the state store.\n */\n", - "excerptTokens": [ - { - "kind": "Content", - "text": "type: " - }, - { - "kind": "Content", - "text": "`${" - }, - { - "kind": "Reference", - "text": "ComponentType", - "canonicalReference": "@openfunction/functions-framework!ComponentType:enum" - }, - { - "kind": "Content", - "text": "}.${string}`" - }, - { - "kind": "Content", - "text": ";" - } - ], - "isReadonly": false, - "isOptional": false, - "releaseTag": "Public", - "name": "type", - "propertyTypeTokenRange": { - "startIndex": 1, - "endIndex": 4 - } - }, - { - "kind": "PropertySignature", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec#version:member", - "docComment": "/**\n * The version of the component\n */\n", - "excerptTokens": [ - { - "kind": "Content", - "text": "version: " - }, - { - "kind": "Content", - "text": "string" - }, - { - "kind": "Content", - "text": ";" - } - ], - "isReadonly": false, - "isOptional": false, - "releaseTag": "Public", - "name": "version", - "propertyTypeTokenRange": { - "startIndex": 1, - "endIndex": 2 - } - } - ], - "extendsTokenRanges": [] - }, { "kind": "Enum", "canonicalReference": "@openfunction/functions-framework!ComponentType:enum", @@ -972,8 +859,8 @@ }, { "kind": "Reference", - "text": "ComponentSpec", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec:interface" + "text": "OpenFunctionComponent", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionComponent:interface" }, { "kind": "Content", @@ -2253,8 +2140,8 @@ }, { "kind": "Reference", - "text": "ComponentSpec", - "canonicalReference": "@openfunction/functions-framework!ComponentSpec:interface" + "text": "OpenFunctionComponent", + "canonicalReference": "@openfunction/functions-framework!OpenFunctionComponent:interface" }, { "kind": "Content", @@ -2861,7 +2748,7 @@ { "kind": "Property", "canonicalReference": "@openfunction/functions-framework!OpenFunctionRuntime#state:member", - "docComment": "/**\n * The state store and its operations\n */\n", + "docComment": "/**\n * The promise that handle data by state store.\n */\n", "excerptTokens": [ { "kind": "Content", @@ -2878,7 +2765,7 @@ }, { "kind": "Content", - "text": ";\n get: (data: object, db?: string) => " + "text": ";\n get: (data: object, db?: string) => " }, { "kind": "Reference", @@ -2887,7 +2774,16 @@ }, { "kind": "Content", - "text": ";\n getBulk: (data: object, db?: string) => " + "text": "<" + }, + { + "kind": "Reference", + "text": "KeyValueType", + "canonicalReference": "@dapr/dapr!KeyValueType:type" + }, + { + "kind": "Content", + "text": " | string>;\n getBulk: (data: object, db?: string) => " }, { "kind": "Reference", @@ -2896,7 +2792,16 @@ }, { "kind": "Content", - "text": ";\n delete: (data: object, db?: string) => " + "text": "<" + }, + { + "kind": "Reference", + "text": "KeyValueType", + "canonicalReference": "@dapr/dapr!KeyValueType:type" + }, + { + "kind": "Content", + "text": "[]>;\n delete: (data: object, db?: string) => " }, { "kind": "Reference", @@ -2905,7 +2810,7 @@ }, { "kind": "Content", - "text": ";\n transaction: (data: object, db?: string) => " + "text": ";\n transaction: (data: object, db?: string) => " }, { "kind": "Reference", @@ -2914,7 +2819,7 @@ }, { "kind": "Content", - "text": ";\n query: (query: object, db?: string) => " + "text": ";\n query: (query: object, db?: string) => " }, { "kind": "Reference", @@ -2923,7 +2828,16 @@ }, { "kind": "Content", - "text": ";\n }" + "text": "<" + }, + { + "kind": "Reference", + "text": "StateQueryResponseType", + "canonicalReference": "@dapr/dapr!StateQueryResponseType:type" + }, + { + "kind": "Content", + "text": ">;\n }" }, { "kind": "Content", @@ -2936,7 +2850,7 @@ "name": "state", "propertyTypeTokenRange": { "startIndex": 1, - "endIndex": 14 + "endIndex": 20 }, "isStatic": false, "isProtected": false diff --git a/docs/generated/api.md b/docs/generated/api.md index 0d7703d59..2291b8b04 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 } @@ -41,13 +43,6 @@ export interface CloudFunctionsContext { timestamp?: string; } -// @public -export interface ComponentSpec { - metadata?: Record; - type: `${ComponentType}.${string}`; - version: string; -} - // @public export enum ComponentType { Binding = "bindings", @@ -64,7 +59,7 @@ export class ContextUtils { static IsBindingComponent(component: OpenFunctionComponent): boolean; static IsKnativeRuntime(context: OpenFunctionContext): boolean; static IsPubSubComponent(component: OpenFunctionComponent): boolean; - static IsStateComponent(component: ComponentSpec): boolean; + static IsStateComponent(component: OpenFunctionComponent): boolean; } // @public @@ -145,7 +140,7 @@ export interface OpenFunctionContext { postPlugins?: string[]; prePlugins?: string[]; runtime: `${RuntimeType}` | `${Capitalize}` | `${Uppercase}`; - states?: Record; + states?: Record; version: string; } @@ -167,12 +162,12 @@ export abstract class OpenFunctionRuntime { GRPC: string; }; abstract get state(): { - 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; + 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; }; // Warning: (ae-forgotten-export) The symbol "OpenFunctionTrigger" needs to be exported by the entry point index.d.ts protected trigger?: OpenFunctionTrigger; From 797395b11c73015c8d0081bfea2159a32912e9ec Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Wed, 12 Jul 2023 16:27:53 +0800 Subject: [PATCH 6/7] =?UTF-8?q?=F0=9F=A6=84=20refactor:=20use=20lodash=20t?= =?UTF-8?q?o=20make=20code=20more=20elegant?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- docs/generated/api.json | 86 +---------------- docs/generated/api.md | 10 +- src/openfunction/runtime.ts | 79 +++++++++------- test/conformance/.env-cmdrc.js | 26 +++++ test/conformance/function.js | 88 ++++++++++++++++- test/conformance/package.json | 22 ++++- test/data/mock/index.ts | 1 - test/data/mock/payload.ts | 108 +++++++++++++++++++++ test/data/mock/statestore.ts | 124 ------------------------ test/integration/http_statestore.ts | 141 +++++++++++----------------- 10 files changed, 342 insertions(+), 343 deletions(-) delete mode 100644 test/data/mock/statestore.ts diff --git a/docs/generated/api.json b/docs/generated/api.json index f3a690c46..bc9797724 100644 --- a/docs/generated/api.json +++ b/docs/generated/api.json @@ -2754,90 +2754,10 @@ "kind": "Content", "text": "abstract get state(): " }, - { - "kind": "Content", - "text": "{\n save: (data: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": ";\n get: (data: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": "<" - }, - { - "kind": "Reference", - "text": "KeyValueType", - "canonicalReference": "@dapr/dapr!KeyValueType:type" - }, - { - "kind": "Content", - "text": " | string>;\n getBulk: (data: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": "<" - }, { "kind": "Reference", - "text": "KeyValueType", - "canonicalReference": "@dapr/dapr!KeyValueType:type" - }, - { - "kind": "Content", - "text": "[]>;\n delete: (data: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": ";\n transaction: (data: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": ";\n query: (query: object, db?: string) => " - }, - { - "kind": "Reference", - "text": "Promise", - "canonicalReference": "!Promise:interface" - }, - { - "kind": "Content", - "text": "<" - }, - { - "kind": "Reference", - "text": "StateQueryResponseType", - "canonicalReference": "@dapr/dapr!StateQueryResponseType:type" - }, - { - "kind": "Content", - "text": ">;\n }" + "text": "StateOperations", + "canonicalReference": "@openfunction/functions-framework!~StateOperations:interface" }, { "kind": "Content", @@ -2850,7 +2770,7 @@ "name": "state", "propertyTypeTokenRange": { "startIndex": 1, - "endIndex": 20 + "endIndex": 2 }, "isStatic": false, "isProtected": false diff --git a/docs/generated/api.md b/docs/generated/api.md index 2291b8b04..11f211478 100644 --- a/docs/generated/api.md +++ b/docs/generated/api.md @@ -161,14 +161,8 @@ export abstract class OpenFunctionRuntime { HTTP: string; GRPC: string; }; - abstract get state(): { - 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; - }; + // 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/runtime.ts b/src/openfunction/runtime.ts index a693b5b86..e873b4c55 100644 --- a/src/openfunction/runtime.ts +++ b/src/openfunction/runtime.ts @@ -1,6 +1,15 @@ 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'; @@ -195,14 +204,20 @@ export abstract class OpenFunctionRuntime { /** * The promise that handle data by state store. */ - abstract get state(): { - 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; - }; + 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; } /** @@ -270,23 +285,26 @@ class DaprRuntime extends OpenFunctionRuntime { */ getState(db?: string): OpenFunctionComponent { // check the states field - if (!this.context.states) { + 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 (!db) { - if (!ContextUtils.IsStateComponent(this.context.states![0])) { + if (isEmpty(db)) { + console.log( + ContextUtils.IsStateComponent(values(this.context.states!)[0]) + ); + if (!ContextUtils.IsStateComponent(values(this.context.states!)[0])) { throw new Error('The state component type is wrong'); } - return Object.values(this.context.states!)[0]; + return values(this.context.states!)[0]; } // or we will use the one specified by user - if (!ContextUtils.IsStateComponent(this.context.states![db])) { + if (!ContextUtils.IsStateComponent(this.context.states![db!])) { throw new Error('The state component type is wrong'); } - return this.context.states[db]; + return values(this.context.states!)[0]; } /** @@ -298,7 +316,7 @@ class DaprRuntime extends OpenFunctionRuntime { #stateSave(data: object, db?: string): Promise { return this.daprClient.state.save( this.getState(db).componentName, - data as KeyValuePairType[] + values(data)[0] as KeyValuePairType[] ); } @@ -309,14 +327,13 @@ class DaprRuntime extends OpenFunctionRuntime { * @returns The promise of the get action being executed. */ #stateGet(data: object, db?: string): Promise { - const data_length = Object.values(data).length; - if (data_length > 1 || data_length <= 0) { + if (isEmpty(data) || size(data) > 1) { throw new Error('State get method: invalid key number'); } return this.daprClient.state.get( this.getState(db).componentName, - Object.values(data)[0] as string + values(data)[0] as string ); } @@ -327,7 +344,7 @@ class DaprRuntime extends OpenFunctionRuntime { * @returns The promise of the getBulk action being executed. */ #stateGetBulk(data: object, db?: string): Promise { - const [keys, parallelism, metadata] = Object.values(data) as [ + const [keys, parallelism, metadata] = values(data) as unknown as [ string[], number, string @@ -346,15 +363,14 @@ class DaprRuntime extends OpenFunctionRuntime { * @param db The state store to delete the data * @returns The promise of the delete action being executed. */ - #stateDelete(data: object, db?: string) { - const data_length = Object.values(data).length; - if (data_length > 1 || data_length <= 0) { - throw new Error('State get method: invalid keys number'); + #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, - Object.values(data)[0] as string + values(data)[0] as string ); } @@ -365,7 +381,7 @@ class DaprRuntime extends OpenFunctionRuntime { * @returns The promise of the transaction action being executed. */ #stateTransaction(data: object, db?: string): Promise { - const [operations, metadata] = Object.values(data) as [ + const [operations, metadata] = values(data) as unknown as [ OperationType[], IRequestMetadata ]; @@ -385,21 +401,14 @@ class DaprRuntime extends OpenFunctionRuntime { #stateQuery(data: object, db?: string): Promise { return this.daprClient.state.query( this.getState(db).componentName, - Object.values(data)[0] as StateQueryType + values(data)[0] as StateQueryType ); } /** * The promise that handle data by state store. */ - get state(): { - 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; - } { + get state(): StateOperations { return { save: this.#stateSave.bind(this), get: this.#stateGet.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/mock/index.ts b/test/data/mock/index.ts index b26288a51..eba4e29ce 100644 --- a/test/data/mock/index.ts +++ b/test/data/mock/index.ts @@ -1,3 +1,2 @@ export * as Context from './context'; export * as Payload from './payload'; -export * as StateStore from './statestore'; 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/data/mock/statestore.ts b/test/data/mock/statestore.ts deleted file mode 100644 index bc52238a9..000000000 --- a/test/data/mock/statestore.ts +++ /dev/null @@ -1,124 +0,0 @@ -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'; - -/** - * The statestore interface of the data. - * @public - */ -export interface IStateStore { - Save: 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: IStateStore = { - Save: [ - { - key: 'weapon', - value: 'DeathStar', - etag: '1234', // some dbs don't support this - }, - { - key: 'planet', - value: { - name: 'Tatooine', - }, - }, - ], - Get: { - key: 'weapon', - }, - GetBulk: { - keys: ['weapon', 'planet'], - parallelism: 10, - }, - Delete: { - key: 'weapon', - }, - Transaction: { - operations: [ - { - operation: 'delete', - request: { - key: 'planet', - }, - }, - { - operation: 'upsert', - request: { - key: '1', - value: { - person: { - org: 'Dev Ops', - id: 1036, - }, - city: 'Seattle', - state: 'WA', - }, - }, - }, - { - operation: 'upsert', - request: { - key: '5', - value: { - person: { - org: 'Hardware', - id: 1007, - }, - city: 'Los Angeles', - state: 'CA', - }, - }, - }, - { - operation: 'upsert', - request: { - key: '3', - value: { - person: { - org: 'Finance', - id: 1071, - }, - city: 'Sacramento', - state: 'CA', - }, - }, - }, - ], - }, - 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 index b31d5a6f8..6550935ac 100644 --- a/test/integration/http_statestore.ts +++ b/test/integration/http_statestore.ts @@ -3,25 +3,28 @@ import {deepStrictEqual} from 'assert'; import * as sinon from 'sinon'; import * as supertest from 'supertest'; import * as shell from 'shelljs'; -import {cloneDeep} from 'lodash'; +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 {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; +import {StateOperations} from '../../src/openfunction/runtime'; -import {Context, StateStore} from '../data/mock'; +import {Context, Payload} from '../data/mock'; +import {KeyValueType} from '@dapr/dapr/types/KeyValue.type'; const TEST_CONTEXT = { ...Context.KnativeBase, }; -const TEST_STATESTORE_SAVE = StateStore.Plain.Save; -const TEST_STATESTORE_GET = StateStore.Plain.Get; -const TEST_STATESTORE_BULK = StateStore.Plain.GetBulk; -const TEST_STATESTORE_DELETE = StateStore.Plain.Delete; -const TEST_STATESTORE_TRANSACTION = StateStore.Plain.Transaction; -const TEST_STATESTORE_QUERY = StateStore.Plain.Query; +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'; @@ -35,7 +38,6 @@ describe('OpenFunction - HTTP StateStore', () => { // Try to start up redis docker container shell.exec( - // 'docker run --name myredis --rm -d -p 6379:6379 redis:latest', 'docker run --name myredis --rm -d -p 6379:6379 redis/redis-stack-server:latest', { silent: true, @@ -75,20 +77,41 @@ describe('OpenFunction - HTTP StateStore', () => { name: 'Get data', operation: 'get', tosend: TEST_STATESTORE_GET, - expect: 'DeathStar', + expect: { + city: 'Seattle', + person: { + id: 1036, + org: 'Dev Ops', + }, + state: 'WA', + }, }, { name: 'GetBulk data', - operation: 'getbulk', + operation: 'getBulk', tosend: TEST_STATESTORE_BULK, expect: [ { - key: 'weapon', - data: 'DeathStar', + data: { + city: 'Seattle', + person: { + id: 1036, + org: 'Dev Ops', + }, + state: 'WA', + }, + key: '1', }, { - key: 'planet', - data: {name: 'Tatooine'}, + data: { + city: 'Portland', + person: { + id: 1028, + org: 'Hardware', + }, + state: 'OR', + }, + key: '2', }, ], }, @@ -111,6 +134,7 @@ describe('OpenFunction - HTTP StateStore', () => { // expect: undefined, }, ]; + for (const test of testData) { it(test.name, async () => { const context = cloneDeep(TEST_CONTEXT); @@ -118,76 +142,21 @@ describe('OpenFunction - HTTP StateStore', () => { const server = getServer( async (ctx: OpenFunctionRuntime, data: {}) => { if (!test.operation) throw new Error('I crashed'); - switch (test.operation) { - case 'save': - await ctx.state - .save(data, 'redis') - .then(res => { - deepStrictEqual(res, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - case 'get': - await ctx.state - .get(data, 'redis') - .then(res => { - deepStrictEqual(res, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - case 'getbulk': - await ctx.state - .getBulk(data, 'redis') - .then(res => { - const promise_data_remove_etag = res.map(obj => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const {etag, ...rest} = obj; - return rest; - }); - deepStrictEqual(promise_data_remove_etag, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - case 'delete': - await ctx.state - .delete(data, 'redis') - .then(res => { - deepStrictEqual(res, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - case 'transaction': - await ctx.state - .transaction(data, 'redis') - .then(res => { - deepStrictEqual(res, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - case 'query': - await ctx.state - .query(data, 'redis') - .then(res => { - console.log(res); - // deepStrictEqual(Object.values(res)[0].value, test.expect); - }) - .catch(err => { - console.log(err); - }); - break; - default: - throw new Error(`Unknown operation: ${test.operation}`); - } + + 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); }, From 5447a42b65446df1a954e99b6848bb113d328796 Mon Sep 17 00:00:00 2001 From: yi-ge-dian Date: Wed, 12 Jul 2023 16:55:17 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=F0=9F=8C=88=20style:=20cosm:=20remove=20co?= =?UTF-8?q?nsole.log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yi-ge-dian --- src/openfunction/runtime.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/openfunction/runtime.ts b/src/openfunction/runtime.ts index e873b4c55..8730602ac 100644 --- a/src/openfunction/runtime.ts +++ b/src/openfunction/runtime.ts @@ -291,9 +291,6 @@ class DaprRuntime extends OpenFunctionRuntime { // if you don't specify the db, we will use the first one defined in the context if (isEmpty(db)) { - console.log( - ContextUtils.IsStateComponent(values(this.context.states!)[0]) - ); if (!ContextUtils.IsStateComponent(values(this.context.states!)[0])) { throw new Error('The state component type is wrong'); }