port schema modules from crystallib
This commit is contained in:
112
lib/schemas/openrpc/README.md
Normal file
112
lib/schemas/openrpc/README.md
Normal file
@@ -0,0 +1,112 @@
|
||||
# OpenRPC
|
||||
|
||||
OpenRPC V library. Model for OpenRPC, client code generation, and specification generation from code.
|
||||
|
||||
## Definitions
|
||||
|
||||
- OpenRPC Specifications: Specifications that define standards for describing JSON-RPC API's.
|
||||
|
||||
- [OpenRPC Document](https://spec.open-rpc.org/#openrpc-document): "A document that defines or describes an API conforming to the OpenRPC Specification."
|
||||
|
||||
- OpenRPC Client: An API Client (using either HTTP or Websocket) that governs functions (one per RPC Method defined in OpenRPC Document) to communicate with RPC servers and perform RPCs.
|
||||
|
||||
## OpenRPC Document Generation
|
||||
|
||||
The OpenRPC Document Generator generates a [JSON-RPC](https://www.jsonrpc.org/) API description conforming to [OpenRPC Specifications](https://spec.open-rpc.org/), from an OpenRPC Client module written in V.
|
||||
|
||||
To use the document generator, you need to have a V module with at least one V file.
|
||||
|
||||
The recommended way to generate an OpenRPC document for a V module is to use the OpenRPC CLI. Note below: if you are not using the openrpc cli as a binary executable, replace `openrpc` with `path_to_herolib.core.openrpc/cli/cli.v` in the commands below
|
||||
|
||||
`openrpc docgen .`
|
||||
|
||||
Running this command in a V client module's directory will generate an OpenRPC document from the code in the module and output it to a openrpc.json file in the same directory. See [annotation code for openrpc document generation](#annotating-code-for-openrpc-document-generation) for information on how to format V client module to be compatible for OpenRPC Document Generation.
|
||||
|
||||
The following output parameter and source path argument can be used to generate an OpenRPC Document for a module that is in a different directory, and output the document in a desired path.
|
||||
|
||||
`openrpc docgen -o <output_path> <source_path>`
|
||||
|
||||
Run `openrpc docgen help` for more information. The CLI also has flags for filtering files and directories on input source, or choosing to generate document for only public struct and functions.
|
||||
|
||||
|
||||
### Annotating code for OpenRPC Document Generation
|
||||
|
||||
The docgen module uses the [codeparser module](../../codeparser) to parse the source code for document generation. Therefore, the V code from which an OpenRPC Document will be generated must conform to the [V Annotation guidelines for code parsing](../../codeparser/README.md/#annotating-code-in-v), such that the document generator can harvest method and schema information such as descriptions from the comments in the code.
|
||||
|
||||
Below is an example OpenRPC compliant JSON Method and Schema descriptions generated from a properly annotated v file.
|
||||
|
||||
```go
|
||||
// this is a description of the struct
|
||||
struct Example {
|
||||
field0 string // this comment describes field0
|
||||
field1 int // this comment describes field1
|
||||
}
|
||||
|
||||
// some_function is described by the words following the functions name
|
||||
// - param0: this sentence after the colon describes param0
|
||||
// - param1: this sentence after the colon describes param1
|
||||
// returns the desired result, this sentence after the comma describes 'the desired result'
|
||||
fn some_function(param0 string, param1 int) result []string {}
|
||||
```
|
||||
|
||||
The following OpenRPC JSON Descriptions are generated from the above code:
|
||||
|
||||
```js
|
||||
// schema generated from Example struct
|
||||
{
|
||||
'name': 'Example'
|
||||
'description': 'this is a description of the struct'
|
||||
'properties': [
|
||||
'field0': {
|
||||
'type': 'string'
|
||||
},
|
||||
'field1': {
|
||||
'type': 'int'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// method generated from some_function function
|
||||
{
|
||||
'name': 'some_function'
|
||||
'description': 'is described by the words following the functions name'
|
||||
'params': [
|
||||
{
|
||||
'name': 'param0'
|
||||
'description': 'this sentence after the colon describes param0'
|
||||
'schema': {
|
||||
'type': 'string'
|
||||
}
|
||||
},
|
||||
{
|
||||
'name': 'param1'
|
||||
'description': 'this sentence after the colon describes param1'
|
||||
'schema': {
|
||||
'type': 'int'
|
||||
}
|
||||
}
|
||||
]
|
||||
'result': {
|
||||
'name': 'the desired result'
|
||||
'description': 'this sentence after the comma describes \'the desired result\''
|
||||
'schema': {
|
||||
'type': 'array'
|
||||
'items': {
|
||||
'type': 'string'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
## Examples
|
||||
|
||||
The best way to understand how the document generation works is through the examples in this module
|
||||
|
||||
### Pet Store Example
|
||||
|
||||
Run this command from the root of the openrpc module.
|
||||
|
||||
```bash
|
||||
v run cli/cli.v docgen -t 'PetStore API' -o examples/petstore_client -f 'client.v' examples/petstore_client
|
||||
```
|
||||
This generates an OpenRPC Document called PetStore API from the code in examples/petstore_client, excluding the client.v file, and writes it to examples/petstore_client/openrpc.json
|
||||
103
lib/schemas/openrpc/codegen/docgen.v
Normal file
103
lib/schemas/openrpc/codegen/docgen.v
Normal file
@@ -0,0 +1,103 @@
|
||||
module codegen
|
||||
|
||||
// import freeflowuniverse.herolib.core.code
|
||||
// import freeflowuniverse.herolib.ui.console
|
||||
// import freeflowuniverse.herolib.core.texttools
|
||||
|
||||
// // configuration parameters for OpenRPC Document generation.
|
||||
// @[params]
|
||||
// pub struct DocGenConfig {
|
||||
// title string // Title of the JSON-RPC API
|
||||
// description string // Description of the JSON-RPC API
|
||||
// version string = '1.0.0' // OpenRPC Version used
|
||||
// source string // Source code directory to generate doc from
|
||||
// strict bool // Strict mode generates document for only methods and struct with the attribute `openrpc`
|
||||
// exclude_dirs []string // directories to be excluded when parsing source for document generation
|
||||
// exclude_files []string // files to be excluded when parsing source for document generation
|
||||
// only_pub bool // excludes all non-public declarations from document generation
|
||||
// }
|
||||
|
||||
// // docgen returns OpenRPC Document struct for JSON-RPC API defined in the config params.
|
||||
// // returns generated OpenRPC struct which can be encoded into json using `OpenRPC.encode()`
|
||||
// pub fn docgen(config DocGenConfig) !OpenRPC {
|
||||
// $if debug {
|
||||
// console.print_debug('Generating OpenRPC Document from path: ${config.source}')
|
||||
// }
|
||||
|
||||
// // parse source code into code items
|
||||
// code := codeparser.parse_v(config.source,
|
||||
// exclude_dirs: config.exclude_dirs
|
||||
// exclude_files: config.exclude_files
|
||||
// only_pub: config.only_pub
|
||||
// recursive: true
|
||||
// )!
|
||||
|
||||
// mut schemas := map[string]jsonschema.SchemaRef{}
|
||||
// mut methods := []Method{}
|
||||
|
||||
// // generate JSONSchema compliant schema definitions for structs in code
|
||||
// for struct_ in code.filter(it is Struct).map(it as Struct) {
|
||||
// schema := jsonschema.struct_to_schema(struct_)
|
||||
// schemas[struct_.name] = schema
|
||||
// }
|
||||
|
||||
// // generate JSONSchema compliant schema definitions for sumtypes in code
|
||||
// for sumtype in code.filter(it is Sumtype).map(it as Sumtype) {
|
||||
// schema := jsonschema.sumtype_to_schema(sumtype)
|
||||
// schemas[sumtype.name] = schema
|
||||
// }
|
||||
|
||||
// // generate OpenRPC compliant method definitions for functions in code
|
||||
// for function in code.filter(it is Function).map(it as Function) {
|
||||
// method := fn_to_method(function)
|
||||
// methods << method
|
||||
// }
|
||||
|
||||
// return OpenRPC{
|
||||
// info: Info{
|
||||
// title: config.title
|
||||
// version: config.version
|
||||
// }
|
||||
// methods: methods
|
||||
// components: Components{
|
||||
// schemas: schemas
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // fn_to_method turns a codemodel function into a openrpc method description
|
||||
// fn fn_to_method(function Function) Method {
|
||||
// $if debug {
|
||||
// println('Creating openrpc method description for function: ${function.name}')
|
||||
// }
|
||||
|
||||
// params := params_to_descriptors(function.params)
|
||||
// result_schema := jsonschema.typesymbol_to_schema(function.result.typ.symbol)
|
||||
|
||||
// // if result name isn't set, set it to
|
||||
// result_name := if function.result.name != '' {
|
||||
// function.result.name
|
||||
// } else {
|
||||
// function.result.typ.symbol
|
||||
// }
|
||||
|
||||
// result := ContentDescriptor{
|
||||
// name: result_name
|
||||
// schema: result_schema
|
||||
// description: function.result.description
|
||||
// }
|
||||
|
||||
// pascal_name := texttools.name_fix_snake_to_pascal(function.name)
|
||||
// function_name := if function.mod != '' {
|
||||
// '${function.mod}.${pascal_name}'
|
||||
// } else {
|
||||
// pascal_name
|
||||
// }
|
||||
|
||||
// return Method{
|
||||
// name: function_name
|
||||
// description: function.description
|
||||
// params: params
|
||||
// result: result
|
||||
// }
|
||||
// }
|
||||
45
lib/schemas/openrpc/codegen/generate.v
Normal file
45
lib/schemas/openrpc/codegen/generate.v
Normal file
@@ -0,0 +1,45 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { VFile, File, Function, Struct , Module}
|
||||
import freeflowuniverse.herolib.schemas.openrpc {OpenRPC}
|
||||
|
||||
// pub struct OpenRPCCode {
|
||||
// pub mut:
|
||||
// openrpc_json File
|
||||
// handler VFile
|
||||
// handler_test VFile
|
||||
// client VFile
|
||||
// client_test VFile
|
||||
// server VFile
|
||||
// server_test VFile
|
||||
// }
|
||||
|
||||
|
||||
pub fn generate_module(o OpenRPC, receiver Struct, methods_map map[string]Function, objects_map map[string]Struct) !Module {
|
||||
openrpc_json := o.encode()!
|
||||
openrpc_file := File{
|
||||
name: 'openrpc'
|
||||
extension: 'json'
|
||||
content: openrpc_json
|
||||
}
|
||||
|
||||
client_file := generate_client_file(o, objects_map)!
|
||||
client_test_file := generate_client_test_file(o, methods_map, objects_map)!
|
||||
|
||||
handler_file := generate_handler_file(o, receiver, methods_map, objects_map)!
|
||||
handler_test_file := generate_handler_test_file(o, receiver, methods_map, objects_map)!
|
||||
|
||||
interface_file := generate_interface_file(o)!
|
||||
interface_test_file := generate_interface_test_file(o)!
|
||||
|
||||
return Module{
|
||||
files: [
|
||||
client_file
|
||||
client_test_file
|
||||
handler_file
|
||||
handler_test_file
|
||||
interface_file
|
||||
interface_test_file
|
||||
]
|
||||
}
|
||||
}
|
||||
71
lib/schemas/openrpc/codegen/generate_client.v
Normal file
71
lib/schemas/openrpc/codegen/generate_client.v
Normal file
@@ -0,0 +1,71 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { VFile, CodeItem, CustomCode, Function, Struct, parse_function }
|
||||
// import freeflowuniverse.herolib.schemas.jsonrpc.codegen {generate_client_struct}
|
||||
import freeflowuniverse.herolib.schemas.openrpc {OpenRPC}
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
|
||||
// generate_structs geenrates struct codes for schemas defined in an openrpc document
|
||||
pub fn generate_client_file(o OpenRPC, object_map map[string]Struct) !VFile {
|
||||
name := texttools.name_fix(o.info.title)
|
||||
client_struct_name := '${o.info.title}Client'
|
||||
// client_struct := generate_client_struct(client_struct_name)
|
||||
|
||||
mut items := []CodeItem{}
|
||||
// code << client_struct
|
||||
// code << jsonrpc.generate_ws_factory_code(client_struct_name)!
|
||||
// methods := jsonrpc.generate_client_methods(client_struct, o.methods.map(it.to_code()!))!
|
||||
// imports := [code.parse_import('freeflowuniverse.herolib.schemas.jsonrpc'),
|
||||
// code.parse_import('freeflowuniverse.herolib.schemas.rpcwebsocket'),
|
||||
// code.parse_import('log')]
|
||||
// code << methods.map(CodeItem(it))
|
||||
mut file := VFile{
|
||||
name: 'client'
|
||||
mod: name
|
||||
// imports: imports
|
||||
items: items
|
||||
}
|
||||
for key, object in object_map {
|
||||
file.add_import(mod: object.mod, types: [object.name])!
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
// generate_structs generates struct codes for schemas defined in an openrpc document
|
||||
pub fn generate_client_test_file(o OpenRPC, methods_map map[string]Function, object_map map[string]Struct) !VFile {
|
||||
name := texttools.name_fix(o.info.title)
|
||||
// client_struct_name := '${o.info.title}Client'
|
||||
// client_struct := jsonrpc.generate_client_struct(client_struct_name)
|
||||
|
||||
// code << client_struct
|
||||
// code << jsonrpc.(client_struct_name)
|
||||
// methods := jsonrpc.generate_client_methods(client_struct, o.methods.map(Function{name: it.name}))!
|
||||
|
||||
mut fn_test_factory := parse_function('fn test_new_ws_client() !')!
|
||||
fn_test_factory.body = "mut client := new_ws_client(address:'ws://127.0.0.1:\${port}')!"
|
||||
|
||||
mut items := []CodeItem{}
|
||||
items << CustomCode{'const port = 3100'}
|
||||
items << fn_test_factory
|
||||
for key, method in methods_map {
|
||||
mut func := parse_function('fn test_${method.name}() !')!
|
||||
func_call := method.generate_call(receiver: 'client')!
|
||||
func.body = "mut client := new_ws_client(address:'ws://127.0.0.1:\${port}')!\n${func_call}"
|
||||
items << func
|
||||
}
|
||||
mut file := VFile{
|
||||
name: 'client_test'
|
||||
mod: name
|
||||
imports: [
|
||||
code.parse_import('freeflowuniverse.herolib.schemas.jsonrpc'),
|
||||
code.parse_import('freeflowuniverse.herolib.schemas.rpcwebsocket'),
|
||||
code.parse_import('log'),
|
||||
]
|
||||
items: items
|
||||
}
|
||||
|
||||
for key, object in object_map {
|
||||
file.add_import(mod: object.mod, types: [object.name])!
|
||||
}
|
||||
return file
|
||||
}
|
||||
108
lib/schemas/openrpc/codegen/generate_handler.v
Normal file
108
lib/schemas/openrpc/codegen/generate_handler.v
Normal file
@@ -0,0 +1,108 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { VFile, CodeItem, Param, CustomCode, Function, Result, Struct, parse_import }
|
||||
import freeflowuniverse.herolib.schemas.openrpc {OpenRPC}
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
import rand
|
||||
|
||||
pub fn generate_handler_file(o OpenRPC, receiver Struct, method_map map[string]Function, object_map map[string]Struct) !VFile {
|
||||
name := texttools.name_fix(o.info.title)
|
||||
|
||||
imports := [
|
||||
parse_import('freeflowuniverse.herolib.schemas.jsonrpc'),
|
||||
parse_import('json'),
|
||||
parse_import('x.json2'),
|
||||
parse_import('import freeflowuniverse.herolib.core.texttools'),
|
||||
]
|
||||
|
||||
mut file := VFile{
|
||||
name: 'handler'
|
||||
mod: name
|
||||
imports: imports
|
||||
// TODO
|
||||
// items: jsonrpc.generate_handler(
|
||||
// methods: method_map.values()
|
||||
// receiver: receiver
|
||||
// )!
|
||||
}
|
||||
|
||||
for key, object in object_map {
|
||||
file.add_import(mod: object.mod, types: [object.name])!
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
pub fn generate_handler_test_file(o OpenRPC, receiver Struct, method_map map[string]Function, object_map map[string]Struct) !VFile {
|
||||
name := texttools.name_fix(o.info.title)
|
||||
|
||||
handler_name := texttools.name_fix_pascal_to_snake(receiver.name)
|
||||
|
||||
consts := CustomCode{"const actor_name = '${handler_name}_test_actor'"}
|
||||
clean_code := 'mut actor := get(name: actor_name)!\nactor.backend.reset()!'
|
||||
|
||||
testsuite_begin := Function{
|
||||
name: 'testsuite_begin'
|
||||
body: clean_code
|
||||
}
|
||||
|
||||
testsuite_end := Function{
|
||||
name: 'testsuite_end'
|
||||
body: clean_code
|
||||
}
|
||||
|
||||
mut handle_tests := []Function{}
|
||||
for key, method in method_map {
|
||||
if method.params.len == 0 {
|
||||
continue
|
||||
}
|
||||
if method.params[0].typ.symbol[0].is_capital() {
|
||||
continue
|
||||
}
|
||||
method_handle_test := Function{
|
||||
name: 'test_handle_${method.name}'
|
||||
result: Param{
|
||||
is_result: true
|
||||
}
|
||||
body: "mut handler := ${receiver.name}Handler {${handler_name}.get(name: actor_name)!}
|
||||
request := new_jsonrpcrequest[${method.params[0].typ.symbol}]('${method.name}', ${get_mock_value(method.params[0].typ.symbol)!})
|
||||
response_json := handler.handle(request.to_json())!"
|
||||
}
|
||||
handle_tests << method_handle_test
|
||||
}
|
||||
|
||||
mut items := []CodeItem{}
|
||||
|
||||
items = [
|
||||
consts,
|
||||
testsuite_begin,
|
||||
testsuite_end,
|
||||
]
|
||||
|
||||
items << handle_tests.map(CodeItem(it))
|
||||
|
||||
imports := parse_import('freeflowuniverse.herolib.schemas.jsonrpc {new_jsonrpcrequest, jsonrpcresponse_decode, jsonrpcerror_decode}')
|
||||
|
||||
mut file := VFile{
|
||||
name: 'handler_test'
|
||||
mod: name
|
||||
imports: [imports]
|
||||
items: items
|
||||
}
|
||||
|
||||
for key, object in object_map {
|
||||
file.add_import(mod: object.mod, types: [object.name])!
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
fn get_mock_value(typ string) !string {
|
||||
if typ == 'string' {
|
||||
return "'mock_string_${rand.string(3)}'"
|
||||
} else if typ == 'int' || typ == 'u32' {
|
||||
return '42'
|
||||
} else {
|
||||
return error('mock values for types other than strings and ints are not yet supported')
|
||||
}
|
||||
}
|
||||
|
||||
// pub fn ()
|
||||
70
lib/schemas/openrpc/codegen/generate_interface.v
Normal file
70
lib/schemas/openrpc/codegen/generate_interface.v
Normal file
@@ -0,0 +1,70 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { VFile, CustomCode, parse_function, parse_import }
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
import freeflowuniverse.herolib.schemas.openrpc {OpenRPC}
|
||||
|
||||
// pub fn (mut handler AccountantHandler) handle_ws(client &websocket.Client, message string) string {
|
||||
// return handler.handle(message) or { panic(err) }
|
||||
// }
|
||||
|
||||
// pub fn run_wsserver(port int) ! {
|
||||
// mut logger := log.Logger(&log.Log{level: .debug})
|
||||
// mut handler := AccountantHandler{get(name: 'accountant')!}
|
||||
// mut server := rpcwebsocket.new_rpcwsserver(port, handler.handle_ws, logger)!
|
||||
// server.run()!
|
||||
// }
|
||||
|
||||
pub fn generate_interface_file(specification OpenRPC) !VFile {
|
||||
name := texttools.name_fix(specification.info.title)
|
||||
|
||||
mut handle_ws_fn := parse_function('pub fn (mut handler ${name.title()}Handler) handle_ws(client &websocket.Client, message string) string ')!
|
||||
handle_ws_fn.body = 'return handler.handle(message) or { panic(err) }'
|
||||
|
||||
mut run_wsserver_fn := parse_function('pub fn run_wsserver(port int) !')!
|
||||
run_wsserver_fn.body = "
|
||||
log_ := log.Log{level: .debug}
|
||||
mut logger := log.Logger(&log_)
|
||||
mut handler := ${name.title()}Handler{get(name: '${name}')!}
|
||||
mut server := rpcwebsocket.new_rpcwsserver(port, handler.handle_ws, logger)!
|
||||
server.run()!"
|
||||
items := handle_ws_fn
|
||||
|
||||
return VFile{
|
||||
mod: name
|
||||
name: 'server'
|
||||
imports: [
|
||||
parse_import('log'),
|
||||
parse_import('net.websocket'),
|
||||
parse_import('freeflowuniverse.herolib.schemas.rpcwebsocket {RpcWsServer}'),
|
||||
]
|
||||
items: [
|
||||
handle_ws_fn, run_wsserver_fn
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_interface_test_file(specification OpenRPC) !VFile {
|
||||
name := texttools.name_fix(specification.info.title)
|
||||
// mut handle_ws_fn := parse_function('pub fn (mut handler ${name.title()}Handler) handle_ws(client &websocket.Client, message string) string ')!
|
||||
// handle_ws_fn.body = "return handler.handle(message) or { panic(err) }"
|
||||
|
||||
// mut run_wsserver_fn := parse_function('pub fn run_wsserver(port int) !')!
|
||||
// run_wsserver_fn.body = "mut logger := log.Logger(&log.Log{level: .debug})
|
||||
// mut handler := ${name.title()}Handler{get(name: '${name}')!}
|
||||
// mut server := rpcwebsocket.new_rpcwsserver(port, handler.handle_ws, logger)!
|
||||
// server.run()!"
|
||||
// items := handle_ws_fn
|
||||
|
||||
mut test_fn := parse_function('pub fn test_wsserver() !')!
|
||||
test_fn.body = 'spawn run_wsserver(port)'
|
||||
|
||||
return VFile{
|
||||
mod: name
|
||||
name: 'server_test'
|
||||
items: [
|
||||
CustomCode{'const port = 3000'},
|
||||
test_fn,
|
||||
]
|
||||
}
|
||||
}
|
||||
43
lib/schemas/openrpc/codegen/generate_model.v
Normal file
43
lib/schemas/openrpc/codegen/generate_model.v
Normal file
@@ -0,0 +1,43 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { CodeItem }
|
||||
import freeflowuniverse.herolib.schemas.jsonschema { Schema }
|
||||
import freeflowuniverse.herolib.schemas.jsonschema.codegen as jsonschema_codegen { schema_to_code }
|
||||
import freeflowuniverse.herolib.schemas.openrpc {OpenRPC}
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
|
||||
// generate_structs geenrates struct codes for schemas defined in an openrpc document
|
||||
pub fn generate_model(o OpenRPC) ![]CodeItem {
|
||||
components := o.components
|
||||
mut structs := []CodeItem{}
|
||||
for key, schema_ in components.schemas {
|
||||
if schema_ is Schema {
|
||||
mut schema := schema_
|
||||
if schema.title == '' {
|
||||
schema.title = texttools.name_fix_snake_to_pascal(key)
|
||||
}
|
||||
structs << schema_to_code(schema)!
|
||||
}
|
||||
}
|
||||
return structs
|
||||
}
|
||||
|
||||
// pub fn (s Schema) to_struct() code.Struct {
|
||||
// mut attributes := []Attribute{}
|
||||
// if c.depracated {
|
||||
// attributes << Attribute {name: 'deprecated'}
|
||||
// }
|
||||
// if !c.required {
|
||||
// attributes << Attribute {name: 'params'}
|
||||
// }
|
||||
|
||||
// return code.Struct {
|
||||
// name: name
|
||||
// description: summary
|
||||
// required: required
|
||||
// schema: Schema {
|
||||
|
||||
// }
|
||||
// attrs: attributes
|
||||
// }
|
||||
// }
|
||||
49
lib/schemas/openrpc/codegen/generate_model_test.v
Normal file
49
lib/schemas/openrpc/codegen/generate_model_test.v
Normal file
@@ -0,0 +1,49 @@
|
||||
module codegen
|
||||
|
||||
import os
|
||||
import json
|
||||
import freeflowuniverse.herolib.core.code { Alias, Struct }
|
||||
import freeflowuniverse.herolib.core.pathlib
|
||||
import freeflowuniverse.herolib.schemas.openrpc
|
||||
|
||||
const doc_path = '${os.dir(@FILE)}/testdata/openrpc.json'
|
||||
|
||||
fn test_generate_model() ! {
|
||||
mut doc_file := pathlib.get_file(path: doc_path)!
|
||||
content := doc_file.read()!
|
||||
object := openrpc.decode(content)!
|
||||
model := generate_model(object)!
|
||||
|
||||
assert model.len == 3
|
||||
assert model[0] is Alias
|
||||
pet_id := model[0] as Alias
|
||||
assert pet_id.name == 'PetId'
|
||||
assert pet_id.typ.symbol == 'int'
|
||||
|
||||
assert model[1] is Struct
|
||||
pet_struct := model[1] as Struct
|
||||
assert pet_struct.name == 'Pet'
|
||||
assert pet_struct.fields.len == 3
|
||||
|
||||
// test field is `id PetId @[required]`
|
||||
assert pet_struct.fields[0].name == 'id'
|
||||
assert pet_struct.fields[0].typ.symbol == 'PetId'
|
||||
assert pet_struct.fields[0].attrs.len == 1
|
||||
assert pet_struct.fields[0].attrs[0].name == 'required'
|
||||
|
||||
// test field is `name string @[required]`
|
||||
assert pet_struct.fields[1].name == 'name'
|
||||
assert pet_struct.fields[1].typ.symbol == 'string'
|
||||
assert pet_struct.fields[1].attrs.len == 1
|
||||
assert pet_struct.fields[1].attrs[0].name == 'required'
|
||||
|
||||
// test field is `tag string`
|
||||
assert pet_struct.fields[2].name == 'tag'
|
||||
assert pet_struct.fields[2].typ.symbol == 'string'
|
||||
assert pet_struct.fields[2].attrs.len == 0
|
||||
|
||||
assert model[2] is Alias
|
||||
pets_alias := model[2] as Alias
|
||||
assert pets_alias.name == 'Pets'
|
||||
assert pets_alias.typ.symbol == '[]Pet'
|
||||
}
|
||||
146
lib/schemas/openrpc/codegen/generate_openrpc.v
Normal file
146
lib/schemas/openrpc/codegen/generate_openrpc.v
Normal file
@@ -0,0 +1,146 @@
|
||||
module codegen
|
||||
|
||||
// import freeflowuniverse.herolib.schemas.jsonschema
|
||||
// import freeflowuniverse.herolib.core.code { Function, Struct, Sumtype }
|
||||
// import freeflowuniverse.herolib.ui.console
|
||||
// import freeflowuniverse.herolib.core.texttools
|
||||
|
||||
// // configuration parameters for OpenRPC Document generation.
|
||||
// @[params]
|
||||
// pub struct DocGenConfig {
|
||||
// title string // Title of the JSON-RPC API
|
||||
// description string // Description of the JSON-RPC API
|
||||
// version string = '1.0.0' // OpenRPC Version used
|
||||
// source string // Source code directory to generate doc from
|
||||
// strict bool // Strict mode generates document for only methods and struct with the attribute `openrpc`
|
||||
// exclude_dirs []string // directories to be excluded when parsing source for document generation
|
||||
// exclude_files []string // files to be excluded when parsing source for document generation
|
||||
// only_pub bool // excludes all non-public declarations from document generation
|
||||
// }
|
||||
|
||||
// // docgen returns OpenRPC Document struct for JSON-RPC API defined in the config params.
|
||||
// // returns generated OpenRPC struct which can be encoded into json using `OpenRPC.encode()`
|
||||
// pub fn docgen(config DocGenConfig) !OpenRPC {
|
||||
// $if debug {
|
||||
// console.print_debug('Generating OpenRPC Document from path: ${config.source}')
|
||||
// }
|
||||
|
||||
// // parse source code into code items
|
||||
// code := codeparser.parse_v(config.source,
|
||||
// exclude_dirs: config.exclude_dirs
|
||||
// exclude_files: config.exclude_files
|
||||
// only_pub: config.only_pub
|
||||
// recursive: true
|
||||
// )!
|
||||
|
||||
// mut schemas := map[string]jsonschema.SchemaRef{}
|
||||
// mut methods := []Method{}
|
||||
|
||||
// // generate JSONSchema compliant schema definitions for structs in code
|
||||
// for struct_ in code.filter(it is Struct).map(it as Struct) {
|
||||
// schema := jsonschema.struct_to_schema(struct_)
|
||||
// schemas[struct_.name] = schema
|
||||
// }
|
||||
|
||||
// // generate JSONSchema compliant schema definitions for sumtypes in code
|
||||
// for sumtype in code.filter(it is Sumtype).map(it as Sumtype) {
|
||||
// schema := jsonschema.sumtype_to_schema(sumtype)
|
||||
// schemas[sumtype.name] = schema
|
||||
// }
|
||||
|
||||
// // generate OpenRPC compliant method definitions for functions in code
|
||||
// for function in code.filter(it is Function).map(it as Function) {
|
||||
// method := fn_to_method(function)
|
||||
// methods << method
|
||||
// }
|
||||
|
||||
// return OpenRPC{
|
||||
// info: Info{
|
||||
// title: config.title
|
||||
// version: config.version
|
||||
// }
|
||||
// methods: methods
|
||||
// components: Components{
|
||||
// schemas: schemas
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // fn_to_method turns a codemodel function into a openrpc method description
|
||||
// pub fn fn_to_method(function Function) Method {
|
||||
// $if debug {
|
||||
// console.print_debug('Creating openrpc method description for function: ${function.name}')
|
||||
// }
|
||||
|
||||
// params := params_to_descriptors(function.params)
|
||||
// // if result name isn't set, set it to
|
||||
// result_name := if function.result.name != '' {
|
||||
// function.result.name
|
||||
// } else {
|
||||
// function.result.typ.symbol
|
||||
// }
|
||||
|
||||
// // result := ContentDescriptor{
|
||||
// // name: result_name
|
||||
// // schema: result_schema
|
||||
// // description: function.result.description
|
||||
// // }
|
||||
|
||||
// pascal_name := texttools.name_fix_snake_to_pascal(function.name)
|
||||
// function_name := if function.mod != '' {
|
||||
// '${pascal_name}'
|
||||
// } else {
|
||||
// pascal_name
|
||||
// }
|
||||
// m := Method{
|
||||
// name: function_name
|
||||
// description: function.description
|
||||
// params: params
|
||||
// result: param_to_descriptor(function.result)
|
||||
// }
|
||||
|
||||
// return Method{
|
||||
// name: function_name
|
||||
// description: function.description
|
||||
// params: params
|
||||
// result: param_to_descriptor(function.result)
|
||||
// }
|
||||
// }
|
||||
|
||||
// // get_param_descriptors returns content descriptors generated for a list of params
|
||||
// fn params_to_descriptors(params []code.Param) []ContentDescriptorRef {
|
||||
// mut descriptors := []ContentDescriptorRef{}
|
||||
// for param in params {
|
||||
// descriptors << param_to_descriptor(param)
|
||||
// }
|
||||
// return descriptors
|
||||
// }
|
||||
|
||||
// // get_param_descriptors returns content descriptors generated for a list of params
|
||||
// fn param_to_descriptor(param code.Param) ContentDescriptorRef {
|
||||
// schemaref := jsonschema.param_to_schema(param)
|
||||
// return ContentDescriptorRef(ContentDescriptor{
|
||||
// name: param.name
|
||||
// schema: schemaref
|
||||
// description: param.description
|
||||
// required: param.required
|
||||
// })
|
||||
// }
|
||||
|
||||
// // get_param_descriptors returns content descriptors generated for a list of params
|
||||
// pub fn result_to_descriptor(result code.Result) ContentDescriptorRef {
|
||||
// schemaref := jsonschema.result_to_schema(result)
|
||||
|
||||
// name := if result.name != '' {
|
||||
// result.name
|
||||
// } else if result.typ.symbol != '' {
|
||||
// result.typ.symbol
|
||||
// } else {
|
||||
// 'null'
|
||||
// }
|
||||
// return ContentDescriptorRef(ContentDescriptor{
|
||||
// name: name
|
||||
// schema: schemaref
|
||||
// description: result.description
|
||||
// })
|
||||
// }
|
||||
25
lib/schemas/openrpc/codegen/templates/client.v.template
Normal file
25
lib/schemas/openrpc/codegen/templates/client.v.template
Normal file
@@ -0,0 +1,25 @@
|
||||
module @{module}
|
||||
|
||||
import freeflowuniverse.herolib.data.rpcwebsocket
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import log
|
||||
import json
|
||||
|
||||
pub struct @{name}OpenRpcClient {
|
||||
mut:
|
||||
transport &jsonrpc.IRpcTransportClient
|
||||
}
|
||||
|
||||
@[params]
|
||||
pub struct ClientConfig {
|
||||
address string
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
pub fn new_ws_client(config ClientConfig) !PetstoreOpenRpcClient {
|
||||
mut transport := rpcwebsocket.new_rpcwsclient(config.address, config.logger)!
|
||||
spawn transport.run()
|
||||
return PetstoreJsonRpcClient {
|
||||
transport: transport
|
||||
}
|
||||
}
|
||||
205
lib/schemas/openrpc/codegen/testdata/openrpc.json
vendored
Normal file
205
lib/schemas/openrpc/codegen/testdata/openrpc.json
vendored
Normal file
@@ -0,0 +1,205 @@
|
||||
{
|
||||
"openrpc": "1.0.0-rc1",
|
||||
"info": {
|
||||
"version": "1.0.0",
|
||||
"title": "Petstore",
|
||||
"license": {
|
||||
"name": "MIT"
|
||||
}
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"name": "localhost",
|
||||
"url": "http://localhost:8080"
|
||||
}
|
||||
],
|
||||
"methods": [
|
||||
{
|
||||
"name": "list_pets",
|
||||
"summary": "List all pets",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "limit",
|
||||
"description": "How many items to return at one time (max 100)",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pets",
|
||||
"description": "A paged array of pets",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Pets"
|
||||
}
|
||||
},
|
||||
"errors": [
|
||||
{
|
||||
"code": 100,
|
||||
"message": "pets busy"
|
||||
}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"name": "listPetExample",
|
||||
"description": "List pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "limit",
|
||||
"value": 1
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "listPetResultExample",
|
||||
"value": [
|
||||
{
|
||||
"id": 7,
|
||||
"name": "fluffy",
|
||||
"tag": "poodle"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "create_pet",
|
||||
"summary": "Create a pet",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "newPetName",
|
||||
"description": "Name of pet to create",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "newPetTag",
|
||||
"description": "Pet tag to create",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"name": "createPetExample",
|
||||
"description": "Create pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "newPetName",
|
||||
"value": "fluffy"
|
||||
},
|
||||
{
|
||||
"name": "tag",
|
||||
"value": "poodle"
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "listPetResultExample",
|
||||
"value": 7
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"$ref": "#/components/contentDescriptors/PetId"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_pet",
|
||||
"summary": "Info for a specific pet",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"$ref": "#/components/contentDescriptors/PetId"
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet",
|
||||
"description": "Expected response to a valid request",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Pet"
|
||||
}
|
||||
},
|
||||
"examples": [
|
||||
{
|
||||
"name": "getPetExample",
|
||||
"description": "get pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "petId",
|
||||
"value": 7
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "getPetExampleResult",
|
||||
"value": {
|
||||
"name": "fluffy",
|
||||
"tag": "poodle",
|
||||
"id": 7
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"components": {
|
||||
"contentDescriptors": {
|
||||
"PetId": {
|
||||
"name": "petId",
|
||||
"required": true,
|
||||
"description": "The id of the pet to retrieve",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PetId"
|
||||
}
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"PetId": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"Pet": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"name"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/components/schemas/PetId"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"tag": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Pets": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Pet"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
55
lib/schemas/openrpc/codegen/to_code.v
Normal file
55
lib/schemas/openrpc/codegen/to_code.v
Normal file
@@ -0,0 +1,55 @@
|
||||
module codegen
|
||||
|
||||
import freeflowuniverse.herolib.core.code { VFile, CodeItem, CustomCode, Function, Struct, parse_function }
|
||||
import freeflowuniverse.herolib.schemas.jsonschema.codegen as jsonschema_codegen {schemaref_to_type}
|
||||
import freeflowuniverse.herolib.schemas.openrpc {Method, ContentDescriptor}
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
|
||||
// converts OpenRPC Method to Code Function
|
||||
pub fn method_to_function(method Method) !Function {
|
||||
mut params := []code.Param{}
|
||||
for param in method.params {
|
||||
if param is ContentDescriptor {
|
||||
params << content_descriptor_to_parameter(param)!
|
||||
}
|
||||
}
|
||||
result := if method.result is ContentDescriptor {
|
||||
content_descriptor_to_parameter(method.result)!
|
||||
} else {
|
||||
panic('Method must be inflated')
|
||||
}
|
||||
|
||||
return Function{
|
||||
name: texttools.name_fix_pascal_to_snake(method.name)
|
||||
params: params
|
||||
result: result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content_descriptor_to_parameter(cd ContentDescriptor) !code.Param {
|
||||
return code.Param{
|
||||
name: cd.name
|
||||
typ: schemaref_to_type(cd.schema)!
|
||||
}
|
||||
}
|
||||
|
||||
// //
|
||||
// pub fn (s Schema) to_struct() code.Struct {
|
||||
// mut attributes := []Attribute{}
|
||||
// if c.depracated {
|
||||
// attributes << Attribute {name: 'deprecated'}
|
||||
// }
|
||||
// if !c.required {
|
||||
// attributes << Attribute {name: 'params'}
|
||||
// }
|
||||
|
||||
// return code.Struct {
|
||||
// name: name
|
||||
// description: summary
|
||||
// required: required
|
||||
// schema: Schema {
|
||||
|
||||
// }
|
||||
// attrs: attributes
|
||||
// }
|
||||
// }
|
||||
85
lib/schemas/openrpc/decode.v
Normal file
85
lib/schemas/openrpc/decode.v
Normal file
@@ -0,0 +1,85 @@
|
||||
module openrpc
|
||||
|
||||
import json
|
||||
import x.json2 { Any }
|
||||
import freeflowuniverse.herolib.schemas.jsonschema { Reference, decode_schemaref }
|
||||
|
||||
pub fn decode(data string) !OpenRPC {
|
||||
mut object := json.decode(OpenRPC, data) or { return error('Failed to decode json\n${err}') }
|
||||
data_map := json2.raw_decode(data)!.as_map()
|
||||
if 'components' in data_map {
|
||||
object.components = decode_components(data_map) or {
|
||||
return error('Failed to decode components\n${err}')
|
||||
}
|
||||
}
|
||||
|
||||
for i, method in data_map['methods'].arr() {
|
||||
method_map := method.as_map()
|
||||
params_arr := method_map['params'].arr()
|
||||
result := if 'result' in method_map {
|
||||
method_map['result']
|
||||
} else {
|
||||
''
|
||||
}
|
||||
object.methods[i].params = params_arr.map(decode_content_descriptor_ref(it.as_map()) or {
|
||||
return error('Failed to decode params\n${err}')
|
||||
})
|
||||
object.methods[i].result = decode_content_descriptor_ref(result.as_map()) or {
|
||||
return error('Failed to decode result\n${err}')
|
||||
}
|
||||
}
|
||||
// object.methods = decode_method(data_map['methods'].as_array)!
|
||||
return object
|
||||
}
|
||||
|
||||
// fn decode_method(data_map map[string]Any) !Method {
|
||||
// method := Method {
|
||||
// name: data_map['name']
|
||||
// description: data_map['description']
|
||||
// result: json.decode(data_map['result'])
|
||||
// }
|
||||
|
||||
// return method
|
||||
// }
|
||||
|
||||
// fn decode_method_param(data_map map[string]Any) !Method {
|
||||
// method := Method {}
|
||||
|
||||
// return method
|
||||
// }
|
||||
|
||||
fn decode_components(data_map map[string]Any) !Components {
|
||||
mut components := Components{}
|
||||
components_map := data_map['components'].as_map()
|
||||
|
||||
if 'contentDescriptors' in components_map {
|
||||
descriptors_map := components_map['contentDescriptors'].as_map()
|
||||
for key, value in descriptors_map {
|
||||
descriptor := decode_content_descriptor_ref(value.as_map())!
|
||||
components.content_descriptors[key] = descriptor
|
||||
}
|
||||
}
|
||||
|
||||
if 'schemas' in components_map {
|
||||
schemas_map := components_map['schemas'].as_map()
|
||||
for key, value in schemas_map {
|
||||
schema := jsonschema.decode(value.str())!
|
||||
components.schemas[key] = schema
|
||||
}
|
||||
}
|
||||
|
||||
return components
|
||||
}
|
||||
|
||||
fn decode_content_descriptor_ref(data_map map[string]Any) !ContentDescriptorRef {
|
||||
if '\$ref' in data_map {
|
||||
return Reference{
|
||||
ref: data_map['\$ref'].str()
|
||||
}
|
||||
}
|
||||
mut descriptor := json.decode(ContentDescriptor, data_map.str())!
|
||||
if schema_any := data_map['schema'] {
|
||||
descriptor.schema = decode_schemaref(schema_any.as_map())!
|
||||
}
|
||||
return descriptor
|
||||
}
|
||||
18
lib/schemas/openrpc/decode_test.v
Normal file
18
lib/schemas/openrpc/decode_test.v
Normal file
@@ -0,0 +1,18 @@
|
||||
module openrpc
|
||||
|
||||
import json
|
||||
import x.json2
|
||||
import os
|
||||
import freeflowuniverse.herolib.core.pathlib
|
||||
import freeflowuniverse.herolib.schemas.jsonschema
|
||||
|
||||
const doc_path = '${os.dir(@FILE)}/testdata/openrpc.json'
|
||||
|
||||
fn test_decode() ! {
|
||||
mut doc_file := pathlib.get_file(path: openrpc.doc_path)!
|
||||
content := doc_file.read()!
|
||||
object := decode(content)!
|
||||
|
||||
assert object.openrpc == '1.0.0-rc1'
|
||||
assert object.methods.map(it.name) == ['list_pets', 'create_pet', 'get_pet']
|
||||
}
|
||||
56
lib/schemas/openrpc/encode.v
Normal file
56
lib/schemas/openrpc/encode.v
Normal file
@@ -0,0 +1,56 @@
|
||||
module openrpc
|
||||
|
||||
import json
|
||||
import x.json2 { Any }
|
||||
|
||||
// encode encodes an OpenRPC document struct into json string.
|
||||
// eliminates undefined variable by calling prune on the initial encoding.
|
||||
pub fn (doc OpenRPC) encode() !string {
|
||||
encoded := json.encode(doc)
|
||||
raw_decode := json2.raw_decode(encoded)!
|
||||
mut doc_map := raw_decode.as_map()
|
||||
pruned_map := prune(doc_map)
|
||||
return json2.encode_pretty[Any](pruned_map)
|
||||
}
|
||||
|
||||
// prune recursively prunes a map of Any type, pruning map keys where the value is the default value of the variable.
|
||||
// this treats undefined values as null, which is ok for openrpc document encoding.
|
||||
pub fn prune(obj Any) Any {
|
||||
if obj is map[string]Any {
|
||||
mut pruned_map := map[string]Any{}
|
||||
|
||||
for key, val in obj as map[string]Any {
|
||||
if key == '_type' {
|
||||
continue
|
||||
}
|
||||
pruned_val := prune(val)
|
||||
if pruned_val.str() != '' {
|
||||
pruned_map[key] = pruned_val
|
||||
} else if key == 'methods' || key == 'params' {
|
||||
pruned_map[key] = []Any{}
|
||||
}
|
||||
}
|
||||
|
||||
if pruned_map.keys().len != 0 {
|
||||
return pruned_map
|
||||
}
|
||||
} else if obj is []Any {
|
||||
mut pruned_arr := []Any{}
|
||||
|
||||
for val in obj as []Any {
|
||||
pruned_val := prune(val)
|
||||
if pruned_val.str() != '' {
|
||||
pruned_arr << pruned_val
|
||||
}
|
||||
}
|
||||
|
||||
if pruned_arr.len != 0 {
|
||||
return pruned_arr
|
||||
}
|
||||
} else if obj is string {
|
||||
if obj != '' {
|
||||
return obj
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
101
lib/schemas/openrpc/encode_test.v
Normal file
101
lib/schemas/openrpc/encode_test.v
Normal file
@@ -0,0 +1,101 @@
|
||||
module openrpc
|
||||
|
||||
import json
|
||||
import freeflowuniverse.herolib.schemas.jsonschema { Schema, SchemaRef }
|
||||
|
||||
const blank_openrpc = '{
|
||||
"openrpc": "1.0.0",
|
||||
"info": {
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"methods": []
|
||||
}'
|
||||
|
||||
// test if encode can correctly encode a blank OpenRPC
|
||||
fn test_encode_blank() ! {
|
||||
doc := OpenRPC{
|
||||
info: Info{
|
||||
title: ''
|
||||
version: '1.0.0'
|
||||
}
|
||||
methods: []Method{}
|
||||
}
|
||||
encoded := doc.encode()!
|
||||
assert encoded.trim_space().split_into_lines().map(it.trim_space()) == openrpc.blank_openrpc.split_into_lines().map(it.trim_space())
|
||||
}
|
||||
|
||||
// test if can correctly encode an OpenRPC doc with a method
|
||||
fn test_encode_with_method() ! {
|
||||
doc := OpenRPC{
|
||||
info: Info{
|
||||
title: ''
|
||||
version: '1.0.0'
|
||||
}
|
||||
methods: [
|
||||
Method{
|
||||
name: 'method_name'
|
||||
summary: 'summary'
|
||||
description: 'description for this method'
|
||||
deprecated: true
|
||||
params: [
|
||||
ContentDescriptor{
|
||||
name: 'sample descriptor'
|
||||
schema: SchemaRef(Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
},
|
||||
]
|
||||
},
|
||||
]
|
||||
}
|
||||
encoded := doc.encode()!
|
||||
assert encoded == '{
|
||||
"openrpc": "1.0.0",
|
||||
"info": {
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"methods": [
|
||||
{
|
||||
"name": "method_name",
|
||||
"summary": "summary",
|
||||
"description": "description for this method",
|
||||
"params": [
|
||||
{
|
||||
"name": "sample descriptor",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}'
|
||||
}
|
||||
|
||||
// test if can correctly encode a complete OpenRPC doc
|
||||
fn test_encode() ! {
|
||||
doc := OpenRPC{
|
||||
info: Info{
|
||||
title: ''
|
||||
version: '1.0.0'
|
||||
}
|
||||
methods: [
|
||||
Method{
|
||||
name: 'method_name'
|
||||
summary: 'summary'
|
||||
description: 'description for this method'
|
||||
deprecated: true
|
||||
params: [
|
||||
ContentDescriptor{
|
||||
name: 'sample descriptor'
|
||||
schema: SchemaRef(Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
},
|
||||
]
|
||||
},
|
||||
]
|
||||
}
|
||||
encoded := json.encode(doc)
|
||||
assert encoded == '{"openrpc":"1.0.0","info":{"title":"","version":"1.0.0"},"methods":[{"name":"method_name","summary":"summary","description":"description for this method","params":[{"name":"sample descriptor","schema":{"\$schema":"","\$id":"","title":"","description":"","type":"string","properties":{},"additionalProperties":{},"required":[],"ref":"","items":{},"defs":{},"oneOf":[],"_type":"Schema"},"_type":"ContentDescriptor"}],"result":{},"deprecated":true}]}'
|
||||
}
|
||||
26
lib/schemas/openrpc/factory.v
Normal file
26
lib/schemas/openrpc/factory.v
Normal file
@@ -0,0 +1,26 @@
|
||||
module openrpc
|
||||
|
||||
import os
|
||||
|
||||
@[params]
|
||||
pub struct Params {
|
||||
pub:
|
||||
path string // path to openrpc.json file
|
||||
text string // content of openrpc specification text
|
||||
}
|
||||
|
||||
pub fn new(params Params) !OpenRPC {
|
||||
if params.path == '' && params.text == '' {
|
||||
return OpenRPC{}
|
||||
}
|
||||
|
||||
if params.text != '' && params.path != '' {
|
||||
return error('Either provide path or text')
|
||||
}
|
||||
|
||||
text := if params.path != '' {
|
||||
os.read_file(params.path)!
|
||||
} else { params.text }
|
||||
|
||||
return decode(text)!
|
||||
}
|
||||
71
lib/schemas/openrpc/interface.v
Normal file
71
lib/schemas/openrpc/interface.v
Normal file
@@ -0,0 +1,71 @@
|
||||
module openrpc
|
||||
|
||||
import veb
|
||||
import x.json2
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// Main controller for handling RPC requests
|
||||
pub struct Controller {
|
||||
pub:
|
||||
specification OpenRPC @[required] // OpenRPC specification
|
||||
pub mut:
|
||||
handler Handler @[required] // Handles JSON-RPC requests
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
veb.Context
|
||||
}
|
||||
|
||||
// Creates a new Controller instance
|
||||
pub fn new_controller(c Controller) &Controller {
|
||||
return &Controller{...c}
|
||||
}
|
||||
|
||||
// Parameters for running the server
|
||||
@[params]
|
||||
pub struct RunParams {
|
||||
pub:
|
||||
port int = 8080 // Default to port 8080
|
||||
}
|
||||
|
||||
// Starts the server
|
||||
pub fn (mut c Controller) run(params RunParams) {
|
||||
veb.run[Controller, Context](mut c, 8080)
|
||||
}
|
||||
|
||||
// Handles POST requests at the index endpoint
|
||||
@[post]
|
||||
pub fn (mut c Controller) index(mut ctx Context) veb.Result {
|
||||
req_raw := json2.raw_decode(ctx.req.data) or {
|
||||
return ctx.server_error('Invalid JSON body') // Return error if JSON is malformed
|
||||
}
|
||||
|
||||
req_map := req_raw.as_map() // Converts JSON to a map
|
||||
|
||||
// Create a jsonrpc.Request using the decoded data
|
||||
request := jsonrpc.Request{
|
||||
jsonrpc: req_map['jsonrpc'].str()
|
||||
id: req_map['id'].str()
|
||||
method: req_map['method'].str()
|
||||
params: req_map['params'].str()
|
||||
}
|
||||
|
||||
// Process the request with the handler
|
||||
response := c.handler.handle(request) or {
|
||||
return ctx.server_error('Handler error: ${err.msg}')
|
||||
}
|
||||
|
||||
// Return the handler's response as JSON
|
||||
return ctx.json(response)
|
||||
}
|
||||
|
||||
pub struct Handler {
|
||||
specification OpenRPC
|
||||
pub mut:
|
||||
handler fn(jsonrpc.Request) !jsonrpc.Response
|
||||
}
|
||||
|
||||
// Handle a request and return a response
|
||||
pub fn (h Handler) handle(req jsonrpc.Request) !jsonrpc.Response {
|
||||
return h.handler(req)!
|
||||
}
|
||||
41
lib/schemas/openrpc/interface_test.v
Normal file
41
lib/schemas/openrpc/interface_test.v
Normal file
@@ -0,0 +1,41 @@
|
||||
module openrpc
|
||||
|
||||
import os
|
||||
import veb
|
||||
import x.json2 {Any}
|
||||
import net.http {CommonHeader}
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
const specification_path = os.join_path(os.dir(@FILE), '/testdata/openrpc.json')
|
||||
|
||||
// handler for test echoes JSONRPC Request as JSONRPC Response
|
||||
fn handler(request jsonrpc.Request) !jsonrpc.Response {
|
||||
return jsonrpc.Response {
|
||||
jsonrpc: request.jsonrpc
|
||||
id: request.id
|
||||
result: request.params
|
||||
}
|
||||
}
|
||||
|
||||
fn test_new_server() {
|
||||
specification := new(path: specification_path)!
|
||||
new_controller(
|
||||
specification: specification
|
||||
handler: Handler{
|
||||
specification: specification
|
||||
handler: handler
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn test_run_server() {
|
||||
specification := new(path: specification_path)!
|
||||
mut controller := new_controller(
|
||||
specification: specification
|
||||
handler: Handler{
|
||||
specification: specification
|
||||
handler: handler
|
||||
}
|
||||
)
|
||||
spawn controller.run()
|
||||
}
|
||||
225
lib/schemas/openrpc/model.v
Normal file
225
lib/schemas/openrpc/model.v
Normal file
@@ -0,0 +1,225 @@
|
||||
module openrpc
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonschema { Reference, SchemaRef }
|
||||
|
||||
// This is the root object of the OpenRPC document.
|
||||
// The contents of this object represent a whole OpenRPC document.
|
||||
// How this object is constructed or stored is outside the scope of the OpenRPC Specification.
|
||||
pub struct OpenRPC {
|
||||
pub mut:
|
||||
openrpc string = '1.0.0' // This string MUST be the semantic version number of the OpenRPC Specification version that the OpenRPC document uses.
|
||||
info Info // Provides metadata about the API.
|
||||
servers []Server // An array of Server Objects, which provide connectivity information to a target server.
|
||||
methods []Method // The available methods for the API.
|
||||
components Components // An element to hold various schemas for the specification.
|
||||
external_docs []ExternalDocs @[json: externalDocs] // Additional external documentation.
|
||||
}
|
||||
|
||||
// The object provides metadata about the API.
|
||||
// The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.
|
||||
pub struct Info {
|
||||
pub:
|
||||
title string // The title of the application.
|
||||
description string // A verbose description of the application.
|
||||
terms_of_service string @[json: termsOfService] // A URL to the Terms of Service for the API. MUST be in the format of a URL.
|
||||
contact Contact @[omitempty] // The contact information for the exposed API.
|
||||
license License @[omitempty] // The license information for the exposed API.
|
||||
version string @[omitempty] // The version of the OpenRPC document (which is distinct from the OpenRPC Specification version or the API implementation version).
|
||||
}
|
||||
|
||||
// Contact information for the exposed API.
|
||||
pub struct Contact {
|
||||
name string @[omitempty] // The identifying name of the contact person/organization.
|
||||
email string @[omitempty] // The URL pointing to the contact information. MUST be in the format of a URL.
|
||||
url string @[omitempty] // The email address of the contact person/organization. MUST be in the format of an email address.
|
||||
}
|
||||
|
||||
// License information for the exposed API.
|
||||
pub struct License {
|
||||
name string @[omitempty] // The license name used for the API.
|
||||
url string @[omitempty] // A URL to the license used for the API. MUST be in the format of a URL.
|
||||
}
|
||||
|
||||
// An object representing a Server.
|
||||
// TODO: make variables field optional bug fixed: https://github.com/vlang/v/issues/18000
|
||||
// TODO: server name is required but not for version 1.0.0
|
||||
pub struct Server {
|
||||
pub:
|
||||
name string @[omitempty] // A name to be used as the cannonical name for the server.
|
||||
url RuntimeExpression @[omitempty] // A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenRPC document is being served. Server Variables are passed into the Runtime Expression to produce a server URL.
|
||||
summary string @[omitempty] // A short summary of what the server is.
|
||||
description string @[omitempty] // An optional string describing the host designated by the URL.
|
||||
variables map[string]ServerVariable @[omitempty] // A map between a variable name and its value. The value is passed into the Runtime Expression to produce a server URL.
|
||||
}
|
||||
|
||||
// An object representing a Server Variable for server URL template substitution.
|
||||
pub struct ServerVariable {
|
||||
enum_ []string @[json: 'enum'] // An enumeration of string values to be used if the substitution options are from a limited set.
|
||||
default_ string @[json: 'default'; required] // The default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Note this behavior is different than the Schema Object’s treatment of default values, because in those cases parameter values are optional.
|
||||
description string @[omitempty] // An optional description for the server variable. GitHub Flavored Markdown syntax MAY be used for rich text representation.
|
||||
}
|
||||
|
||||
// Describes the interface for the given method name. The method name is used as the method field of the JSON-RPC body. It therefore MUST be unique.
|
||||
// TODO: make result optional once issue is solved: https://github.com/vlang/v/issues/18001
|
||||
pub struct Method {
|
||||
pub mut:
|
||||
name string @[omitempty] // The cannonical name for the method. The name MUST be unique within the methods array.
|
||||
tags []TagRef @[omitempty] // A list of tags for API documentation control. Tags can be used for logical grouping of methods by resources or any other qualifier.
|
||||
summary string @[omitempty] // A short summary of what the method does.
|
||||
description string @[omitempty] // A verbose explanation of the method behavior.
|
||||
external_docs ExternalDocs @[json: externalDocs; omitempty] // Additional external documentation for this method.
|
||||
params []ContentDescriptorRef @[omitempty] // A list of parameters that are applicable for this method. The list MUST NOT include duplicated parameters and therefore require name to be unique. The list can use the Reference Object to link to parameters that are defined by the Content Descriptor Object. All optional params (content descriptor objects with “required”: false) MUST be positioned after all required params in the list.
|
||||
result ContentDescriptorRef @[omitempty] // The description of the result returned by the method. If defined, it MUST be a Content Descriptor or Reference Object. If undefined, the method MUST only be used as a notification.
|
||||
deprecated bool @[omitempty] // Declares this method to be deprecated. Consumers SHOULD refrain from usage of the declared method. Default value is false.
|
||||
servers []Server @[omitempty] // An alternative servers array to service this method. If an alternative servers array is specified at the Root level, it will be overridden by this value.
|
||||
errors []ErrorRef @[omitempty] // A list of custom application defined errors that MAY be returned. The Errors MUST have unique error codes.
|
||||
links []LinkRef @[omitempty] // A list of possible links from this method call.
|
||||
param_structure ParamStructure @[json: paramStructure; omitempty] // The expected format of the parameters. As per the JSON-RPC 2.0 specification, the params of a JSON-RPC request object may be an array, object, or either (represented as by-position, by-name, and either respectively). When a method has a paramStructure value of by-name, callers of the method MUST send a JSON-RPC request object whose params field is an object. Further, the key names of the params object MUST be the same as the contentDescriptor.names for the given method. Defaults to "either".
|
||||
examples []ExamplePairing @[omitempty] // Array of Example Pairing Object where each example includes a valid params-to-result Content Descriptor pairing.
|
||||
}
|
||||
|
||||
enum ParamStructure {
|
||||
either
|
||||
by_name
|
||||
by_position
|
||||
}
|
||||
|
||||
pub type ContentDescriptorRef = ContentDescriptor | Reference
|
||||
|
||||
// Content Descriptors are objects that do just as they suggest - describe content.
|
||||
// They are reusable ways of describing either parameters or result.
|
||||
// They MUST have a schema.
|
||||
pub struct ContentDescriptor {
|
||||
pub mut:
|
||||
name string @[omitempty] // Name of the content that is being described. If the content described is a method parameter assignable by-name, this field SHALL define the parameter’s key (ie name).
|
||||
summary string @[omitempty] // A short summary of the content that is being described.
|
||||
description string @[omitempty] // A verbose explanation of the content descriptor behavior.
|
||||
required bool @[omitempty] // Determines if the content is a required field. Default value is false.
|
||||
schema SchemaRef @[omitempty] // Schema that describes the content.
|
||||
deprecated bool @[omitempty] // Specifies that the content is deprecated and SHOULD be transitioned out of usage. Default value is false.
|
||||
}
|
||||
|
||||
// The Example Pairing object consists of a set of example params and result.
|
||||
// The result is what you can expect from the JSON-RPC service given the exact params.
|
||||
pub struct ExamplePairing {
|
||||
pub mut:
|
||||
name string @[omitempty] // Name for the example pairing.
|
||||
description string @[omitempty] // A verbose explanation of the example pairing.
|
||||
summary string @[omitempty] // Short description for the example pairing.
|
||||
params []ExampleRef @[omitempty] // Example parameters.
|
||||
result ExampleRef @[omitempty] // Example result. When undefined, the example pairing represents usage of the method as a notification.
|
||||
}
|
||||
|
||||
type ExampleRef = Example | Reference
|
||||
|
||||
// The Example object is an object that defines an example that is intended to match the schema of a given Content Descriptor.
|
||||
// Question: how to handle any type for value?
|
||||
pub struct Example {
|
||||
name string @[omitempty] // Cannonical name of the example.
|
||||
summary string @[omitempty] // Short description for the example.
|
||||
description string @[omitempty] // A verbose explanation of the example.
|
||||
value string @[omitempty] // Embedded literal example. The value field and externalValue field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON, use a string value to contain the example, escaping where necessary.
|
||||
external_value string @[json: externalValue; omitempty] // A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON documents. The value field and externalValue field are mutually exclusive.
|
||||
}
|
||||
|
||||
type LinkRef = Link | Reference
|
||||
|
||||
// The Link object represents a possible design-time link for a result. The presence of a link does not guarantee the caller’s ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between results and other methods.
|
||||
// Unlike dynamic links (i.e. links provided in the result payload), the OpenRPC linking mechanism does not require link information in the runtime result.
|
||||
// For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an method and using them as parameters while invoking the linked method.
|
||||
// TODO: change params map's value type to LinkParam once issue is solved: https://github.com/vlang/v/issues/18002
|
||||
pub struct Link {
|
||||
name string // Cannonical name of the link.
|
||||
description string // A description of the link.
|
||||
summary string // Short description for the link.
|
||||
method string // The name of an existing, resolvable OpenRPC method, as defined with a unique method. This field MUST resolve to a unique Method Object. As opposed to Open Api, Relative method values ARE NOT permitted.
|
||||
params map[string]string // A map representing parameters to pass to a method as specified with method. The key is the parameter name to be used, whereas the value can be a constant or a runtime expression to be evaluated and passed to the linked method.
|
||||
server Server // A server object to be used by the target method.
|
||||
}
|
||||
|
||||
// // TODO: handle any, normally should be Any | RuntimeExpression not string
|
||||
// type LinkParam = string | RuntimeExpression
|
||||
|
||||
// Runtime expressions allow the user to define an expression which will evaluate to a string once the desired value(s) are known. They are used when the desired value of a link or server can only be constructed at run time. This mechanism is used by Link Objects and Server Variables.
|
||||
// The runtime expression makes use of JSON Template Language syntax.
|
||||
// The table below provides examples of runtime expressions and examples of their use in a value:
|
||||
// Runtime expressions preserve the type of the referenced value.
|
||||
type RuntimeExpression = string
|
||||
|
||||
pub type ErrorRef = ErrorSpec | Reference
|
||||
|
||||
// TODO: handle any type for data field
|
||||
// Defines an application level error.
|
||||
pub struct ErrorSpec {
|
||||
pub:
|
||||
code int // A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.
|
||||
message string // A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.
|
||||
data SchemaRef // A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
|
||||
}
|
||||
|
||||
// TODO: enforce regex requirements
|
||||
// Holds a set of reusable objects for different aspects of the OpenRPC.
|
||||
// All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.
|
||||
// All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$
|
||||
pub struct Components {
|
||||
pub mut:
|
||||
content_descriptors map[string]ContentDescriptorRef @[json: contentDescriptors] // An object to hold reusable Content Descriptor Objects.
|
||||
schemas map[string]SchemaRef // An object to hold reusable Schema Objects.
|
||||
examples map[string]Example // An object to hold reusable Example Objects.
|
||||
links map[string]Link // An object to hold reusable Link Objects.
|
||||
error map[string]Error // An object to hold reusable Error Objects.
|
||||
example_pairing_objects map[string]ExamplePairing @[json: examplePairingObjects] // An object to hold reusable Example Pairing Objects.
|
||||
tags map[string]Tag // An object to hold reusable Tag Objects.
|
||||
}
|
||||
|
||||
type TagRef = Reference | Tag
|
||||
|
||||
// Adds metadata to a single tag that is used by the Method Object.
|
||||
// It is not mandatory to have a Tag Object per tag defined in the Method Object instances.
|
||||
pub struct Tag {
|
||||
name string // The name of the tag.
|
||||
summary string // A short summary of the tag.
|
||||
description string // A verbose explanation for the tag.
|
||||
external_docs ExternalDocs @[json: externalDocs] // Additional external documentation for this tag.
|
||||
}
|
||||
|
||||
// Allows referencing an external resource for extended documentation.
|
||||
pub struct ExternalDocs {
|
||||
description string // A verbose explanation of the target documentation.
|
||||
url string // The URL for the target documentation. Value MUST be in the format of a URL.
|
||||
}
|
||||
|
||||
pub struct Property {
|
||||
pub:
|
||||
description string @[omitempty] // A description of the property.
|
||||
typ string @[json: 'type'; omitempty] // The type of the property.
|
||||
exclusive_minimum int @[json: exclusiveMinimum; omitempty] // If the value of the property is a number, this defines the minimum value allowed.
|
||||
min_items int @[json: minItems; omitempty] // If the value of the property is an array, this defines the minimum items allowed.
|
||||
unique_items bool @[json: uniqueItems; omitempty] // If the value of the property is an array, this determines if the values in the array MUST be unique.
|
||||
}
|
||||
|
||||
// todo: implement specification extensions
|
||||
|
||||
// pub struct Property {
|
||||
// description string
|
||||
// typ string [json: 'type']
|
||||
// exclusive_minimum int [json: exclusiveMinimum]
|
||||
// min_items int [json: minItems]
|
||||
// unique_items bool [json: uniqueItems]
|
||||
// }
|
||||
|
||||
// pub struct Value {
|
||||
// versions []Version
|
||||
// }
|
||||
|
||||
// pub struct Version {
|
||||
// status string
|
||||
// updated time.Time
|
||||
// id string
|
||||
// urls []URL
|
||||
// }
|
||||
|
||||
// pub struct URL {
|
||||
// href string
|
||||
// rel string
|
||||
// }
|
||||
92
lib/schemas/openrpc/parse_example.v
Normal file
92
lib/schemas/openrpc/parse_example.v
Normal file
@@ -0,0 +1,92 @@
|
||||
module openrpc
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonschema { Reference }
|
||||
import freeflowuniverse.herolib.core.code { Struct, StructField }
|
||||
import json
|
||||
import x.json2
|
||||
|
||||
pub fn parse_example_pairing(text_ string) !ExamplePairing {
|
||||
if !text_.contains('Example:') {
|
||||
return error('no example found fitting format')
|
||||
}
|
||||
mut text := text_.all_after('Example:').trim_space()
|
||||
|
||||
mut pairing := ExamplePairing{}
|
||||
|
||||
if text.contains('assert') {
|
||||
pairing.name = if text.all_before('assert').trim_space() != '' {
|
||||
text.all_before('assert').trim_space()
|
||||
} else {
|
||||
text.all_after('assert').all_before('(').trim_space()
|
||||
}
|
||||
value := text.all_after('==').all_before('//').trim_space()
|
||||
pairing.params = parse_pairing_params(text.all_after('(').all_before(')'))
|
||||
pairing.result = parse_pairing_result(text)
|
||||
description := text.all_after('//').trim_space()
|
||||
}
|
||||
|
||||
return pairing
|
||||
}
|
||||
|
||||
pub fn parse_struct_example(structure Struct) Example {
|
||||
mut val_map := map[string]json2.Any{}
|
||||
for field in structure.fields {
|
||||
example_attr := field.attrs.filter(it.name == 'example')
|
||||
example_val := if example_attr.len == 1 {
|
||||
example_attr[0].arg
|
||||
} else {
|
||||
generate_example_val(field)
|
||||
}
|
||||
val_map[field.name] = example_val
|
||||
}
|
||||
return Example{
|
||||
name: '${structure.name}Example'
|
||||
value: json2.encode(val_map)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_example_val(field StructField) string {
|
||||
return ''
|
||||
}
|
||||
|
||||
pub fn parse_pairing_params(text_ string) []ExampleRef {
|
||||
mut text := text_.trim_space()
|
||||
mut examples := []ExampleRef{}
|
||||
|
||||
if text.is_lower() && !text.contains("'") && !text.contains('"') {
|
||||
examples << Reference{text}
|
||||
} else if text.contains(':') {
|
||||
examples << Example{
|
||||
name: ''
|
||||
value: json.encode(text)
|
||||
}
|
||||
} else {
|
||||
examples1 := text.split(',').map(it.trim_space()).map(ExampleRef(Example{
|
||||
name: ''
|
||||
value: it
|
||||
}))
|
||||
|
||||
examples << examples1
|
||||
}
|
||||
return examples
|
||||
}
|
||||
|
||||
pub fn parse_pairing_result(text_ string) ExampleRef {
|
||||
mut text := text_.trim_space()
|
||||
|
||||
if text.is_lower() {
|
||||
return Reference{text}
|
||||
} else if text.contains(':') {
|
||||
return Example{
|
||||
name: ''
|
||||
value: json.encode(text)
|
||||
}
|
||||
}
|
||||
return Example{}
|
||||
}
|
||||
|
||||
// pub fn parse_example(text string) openrpc.Example {
|
||||
// return Example{
|
||||
|
||||
// }
|
||||
// }
|
||||
58
lib/schemas/openrpc/parse_example_test.v
Normal file
58
lib/schemas/openrpc/parse_example_test.v
Normal file
@@ -0,0 +1,58 @@
|
||||
module openrpc
|
||||
|
||||
import freeflowuniverse.herolib.core.code { Attribute, Struct, StructField, Type }
|
||||
|
||||
const example_txt = "
|
||||
Example: Get pet example.
|
||||
assert some_function('input_string') == 'output_string'
|
||||
"
|
||||
|
||||
// "examples": [
|
||||
// {
|
||||
// "name": "getPetExample",
|
||||
// "description": "get pet example",
|
||||
// "params": [
|
||||
// {
|
||||
// "name": "petId",
|
||||
// "value": 7
|
||||
// }
|
||||
// ],
|
||||
// "result": {
|
||||
// "name": "getPetExampleResult",
|
||||
// "value": {
|
||||
// "name": "fluffy",
|
||||
// "tag": "poodle",
|
||||
// "id": 7
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
fn test_parse_example_pairing() ! {
|
||||
example := parse_example_pairing(openrpc.example_txt)!
|
||||
params := example.params
|
||||
assert params.len == 1
|
||||
param0 := (params[0] as Example)
|
||||
assert param0.value == "'input_string'"
|
||||
}
|
||||
|
||||
const test_struct = Struct{
|
||||
name: 'TestStruct'
|
||||
fields: [
|
||||
StructField{
|
||||
name: 'TestField'
|
||||
typ: Type{
|
||||
symbol: 'int'
|
||||
}
|
||||
attrs: [Attribute{
|
||||
name: 'example'
|
||||
arg: '21'
|
||||
}]
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn test_parse_struct_example() ! {
|
||||
example := parse_struct_example(openrpc.test_struct)
|
||||
// assert example.name == 'TestStructExample'
|
||||
// panic(example)
|
||||
}
|
||||
96
lib/schemas/openrpc/playground.v
Normal file
96
lib/schemas/openrpc/playground.v
Normal file
@@ -0,0 +1,96 @@
|
||||
module openrpc
|
||||
|
||||
import json
|
||||
// import freeflowuniverse.herolib.develop.gittools
|
||||
import freeflowuniverse.herolib.core.pathlib
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
import vweb
|
||||
import os
|
||||
|
||||
pub struct Playground {
|
||||
vweb.Context
|
||||
build pathlib.Path @[vweb_global]
|
||||
}
|
||||
|
||||
@[params]
|
||||
pub struct PlaygroundConfig {
|
||||
pub:
|
||||
dest pathlib.Path @[required]
|
||||
specs []pathlib.Path
|
||||
}
|
||||
|
||||
pub fn export_playground(config PlaygroundConfig) ! {
|
||||
// tw := tailwind.new(
|
||||
// name: 'publisher'
|
||||
// path_build: '${os.dir(@FILE)}'
|
||||
// content_paths: [
|
||||
// '${os.dir(@FILE)}/templates/**/*.html',
|
||||
// ]
|
||||
// )!
|
||||
// css_source := '${os.dir(@FILE)}/templates/css/index.css'
|
||||
// css_dest := '${os.dir(@FILE)}/static/css/index.css'
|
||||
// tw.compile(css_source, css_dest)!
|
||||
// mut gs := gittools.new() or { panic(err) }
|
||||
// mut repo := gs.get_repo(url: 'https://github.com/freeflowuniverse/playground')!
|
||||
|
||||
// playground_dir := repo.get_path()!
|
||||
|
||||
// mut project := npm.new_project(playground_dir)!
|
||||
// project.install()
|
||||
// // export_examples(config.specs, '${playground_dir.path}/src')!
|
||||
// project.build()!
|
||||
// project.export(config.dest)!
|
||||
}
|
||||
|
||||
const build_path = '${os.dir(@FILE)}/playground'
|
||||
|
||||
pub fn new_playground(config PlaygroundConfig) !&Playground {
|
||||
build_dir := pathlib.get_dir(path: openrpc.build_path)!
|
||||
mut pg := Playground{
|
||||
build: build_dir
|
||||
}
|
||||
pg.serve_examples(config.specs) or { return error('failed to serve examples:\n${err}') }
|
||||
pg.mount_static_folder_at('${build_dir.path}/static', '/static')
|
||||
|
||||
mut env_file := pathlib.get_file(path: '${build_dir.path}/env.js')!
|
||||
env_file.write(encode_env(config.specs)!)!
|
||||
pg.serve_static('/env.js', env_file.path)
|
||||
return &pg
|
||||
}
|
||||
|
||||
struct ExampleSpec {
|
||||
name string
|
||||
url string
|
||||
}
|
||||
|
||||
fn encode_env(specs_ []pathlib.Path) !string {
|
||||
mut specs := specs_.clone()
|
||||
mut examples := []ExampleSpec{}
|
||||
|
||||
for mut spec in specs {
|
||||
o := decode(spec.read()!)!
|
||||
name := texttools.name_fix(o.info.title)
|
||||
examples << ExampleSpec{
|
||||
name: name
|
||||
url: '/specs/${name}.json'
|
||||
}
|
||||
}
|
||||
mut examples_str := "window._env_ = { ACTORS: '${json.encode(examples)}' }"
|
||||
return examples_str
|
||||
}
|
||||
|
||||
fn (mut pg Playground) serve_examples(specs_ []pathlib.Path) ! {
|
||||
mut specs := specs_.clone()
|
||||
for mut spec in specs {
|
||||
o := decode(spec.read()!) or {
|
||||
return error('Failed to decode OpenRPC Spec ${spec}:\n${err}')
|
||||
}
|
||||
name := texttools.name_fix(o.info.title)
|
||||
pg.serve_static('/specs/${name}.json', spec.path)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (mut pg Playground) index() vweb.Result {
|
||||
mut index := pathlib.get_file(path: '${pg.build.path}/index.html') or { panic(err) }
|
||||
return pg.html(index.read() or { panic(err) })
|
||||
}
|
||||
3
lib/schemas/openrpc/testdata/method_plain.v
vendored
Normal file
3
lib/schemas/openrpc/testdata/method_plain.v
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
module main
|
||||
|
||||
pub fn method_plain() {}
|
||||
5
lib/schemas/openrpc/testdata/method_with_description.v
vendored
Normal file
5
lib/schemas/openrpc/testdata/method_with_description.v
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
module main
|
||||
|
||||
// method_with_description shows that the parser can parse a method's description
|
||||
// from its comments, even if the comments are multiline.
|
||||
pub fn method_with_description(name string) {}
|
||||
31
lib/schemas/openrpc/testdata/methods.v
vendored
Normal file
31
lib/schemas/openrpc/testdata/methods.v
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
module main
|
||||
|
||||
import freeflowuniverse.herolib.ui.console
|
||||
|
||||
pub fn plain_method() {
|
||||
}
|
||||
|
||||
pub fn method_with_body() {
|
||||
console.print_debug('Example method evoked.')
|
||||
}
|
||||
|
||||
// this method has a comment
|
||||
pub fn method_with_comment() {
|
||||
}
|
||||
|
||||
pub fn method_with_param(param string) {
|
||||
}
|
||||
|
||||
pub fn method_with_return() string {
|
||||
}
|
||||
|
||||
@[params]
|
||||
pub struct Params {
|
||||
param1 int
|
||||
param2 string
|
||||
param3 []int
|
||||
param4 []string
|
||||
}
|
||||
|
||||
pub fn method_with_params(a Params) {
|
||||
}
|
||||
205
lib/schemas/openrpc/testdata/openrpc.json
vendored
Normal file
205
lib/schemas/openrpc/testdata/openrpc.json
vendored
Normal file
@@ -0,0 +1,205 @@
|
||||
{
|
||||
"openrpc": "1.0.0-rc1",
|
||||
"info": {
|
||||
"version": "1.0.0",
|
||||
"title": "Petstore",
|
||||
"license": {
|
||||
"name": "MIT"
|
||||
}
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"name": "localhost",
|
||||
"url": "http://localhost:8080"
|
||||
}
|
||||
],
|
||||
"methods": [
|
||||
{
|
||||
"name": "list_pets",
|
||||
"summary": "List all pets",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "limit",
|
||||
"description": "How many items to return at one time (max 100)",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pets",
|
||||
"description": "A paged array of pets",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Pets"
|
||||
}
|
||||
},
|
||||
"errors": [
|
||||
{
|
||||
"code": 100,
|
||||
"message": "pets busy"
|
||||
}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"name": "listPetExample",
|
||||
"description": "List pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "limit",
|
||||
"value": 1
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "listPetResultExample",
|
||||
"value": [
|
||||
{
|
||||
"id": 7,
|
||||
"name": "fluffy",
|
||||
"tag": "poodle"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "create_pet",
|
||||
"summary": "Create a pet",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "newPetName",
|
||||
"description": "Name of pet to create",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "newPetTag",
|
||||
"description": "Pet tag to create",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"name": "createPetExample",
|
||||
"description": "Create pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "newPetName",
|
||||
"value": "fluffy"
|
||||
},
|
||||
{
|
||||
"name": "tag",
|
||||
"value": "poodle"
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "listPetResultExample",
|
||||
"value": 7
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"$ref": "#/components/contentDescriptors/PetId"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_pet",
|
||||
"summary": "Info for a specific pet",
|
||||
"tags": [
|
||||
{
|
||||
"name": "pets"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"$ref": "#/components/contentDescriptors/PetId"
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet",
|
||||
"description": "Expected response to a valid request",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Pet"
|
||||
}
|
||||
},
|
||||
"examples": [
|
||||
{
|
||||
"name": "getPetExample",
|
||||
"description": "get pet example",
|
||||
"params": [
|
||||
{
|
||||
"name": "petId",
|
||||
"value": 7
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "getPetExampleResult",
|
||||
"value": {
|
||||
"name": "fluffy",
|
||||
"tag": "poodle",
|
||||
"id": 7
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"components": {
|
||||
"contentDescriptors": {
|
||||
"PetId": {
|
||||
"name": "petId",
|
||||
"required": true,
|
||||
"description": "The id of the pet to retrieve",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PetId"
|
||||
}
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"PetId": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"Pet": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"name"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/components/schemas/PetId"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"tag": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Pets": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Pet"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
lib/schemas/openrpc/testdata/petstore_client/README.md
vendored
Normal file
2
lib/schemas/openrpc/testdata/petstore_client/README.md
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
This is a mock client to the Pet Store JSON-RPC API, described by the PetStore OpenRPC Document.
|
||||
The client has comments that are copied from the PetStore OpenRPC Document to demonstrate that document generation from the client results in a similar OpenRPC Document.
|
||||
19
lib/schemas/openrpc/testdata/petstore_client/client.v
vendored
Normal file
19
lib/schemas/openrpc/testdata/petstore_client/client.v
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
module petstore_client
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc { JsonRpcRequest }
|
||||
import net.websocket
|
||||
|
||||
struct Client {
|
||||
mut:
|
||||
ws_client &websocket.Client
|
||||
}
|
||||
|
||||
pub fn new() !Client {
|
||||
address := 'localhost:8000'
|
||||
ws_client := websocket.new_client(address)!
|
||||
return Client{ws_client}
|
||||
}
|
||||
|
||||
fn (mut client Client) send_rpc[T](rpc JsonRpcRequest[T]) ! {
|
||||
client.ws_client.write_string(rpc.to_json())
|
||||
}
|
||||
36
lib/schemas/openrpc/testdata/petstore_client/methods.v
vendored
Normal file
36
lib/schemas/openrpc/testdata/petstore_client/methods.v
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
module petstore_client
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// get_pets finds pets in the system that the user has access to by tags and within a limit
|
||||
// - tags: tags to filter by
|
||||
// - limit: maximum number of results to return
|
||||
// returns pet_list, all pets from the system, that mathes the tags
|
||||
pub fn (mut client Client) get_pets(tags []string, limit int) []Pet {
|
||||
return []Pet{}
|
||||
}
|
||||
|
||||
@[params]
|
||||
struct NewPet {
|
||||
name string @[required]
|
||||
tag string
|
||||
}
|
||||
|
||||
// create_pet creates a new pet in the store. Duplicates are allowed.
|
||||
// - new_pet: Pet to add to the store.
|
||||
// returns pet, the newly created pet
|
||||
pub fn (mut client Client) create_pet(new_pet NewPet) Pet {
|
||||
return Pet{}
|
||||
}
|
||||
|
||||
// get_pet_by_id gets a pet based on a single ID, if the user has access to the pet
|
||||
// - id: ID of pet to fetch
|
||||
// returns pet, pet response
|
||||
pub fn (mut client Client) get_pet_by_id(id int) Pet {
|
||||
return Pet{}
|
||||
}
|
||||
|
||||
// delete_pet_by_id deletes a single pet based on the ID supplied
|
||||
// - id: ID of pet to delete
|
||||
// returns pet, pet deleted
|
||||
pub fn (mut client Client) delete_pet_by_id(id int) {}
|
||||
8
lib/schemas/openrpc/testdata/petstore_client/model.v
vendored
Normal file
8
lib/schemas/openrpc/testdata/petstore_client/model.v
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
module petstore_client
|
||||
|
||||
// a pet struct that represents a pet
|
||||
struct Pet {
|
||||
name string // name of the pet
|
||||
tag string // a tag of the pet, helps finding pet
|
||||
id int // unique indentifier
|
||||
}
|
||||
132
lib/schemas/openrpc/testdata/petstore_client/openrpc.json
vendored
Normal file
132
lib/schemas/openrpc/testdata/petstore_client/openrpc.json
vendored
Normal file
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"openrpc": "1.0.0",
|
||||
"info": {
|
||||
"title": "PetStore API",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"methods": [
|
||||
{
|
||||
"name": "petstore_client.GetPets",
|
||||
"description": "finds pets in the system that the user has access to by tags and within a limit",
|
||||
"params": [
|
||||
{
|
||||
"name": "tags",
|
||||
"description": "tags to filter by",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"description": "maximum number of results to return",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet_list",
|
||||
"description": "all pets from the system, that mathes the tags",
|
||||
"schema": {
|
||||
"$ref": "#\/components\/schemas\/Pet"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "petstore_client.CreatePet",
|
||||
"description": "creates a new pet in the store. Duplicates are allowed.",
|
||||
"params": [
|
||||
{
|
||||
"name": "new_pet",
|
||||
"description": "Pet to add to the store.",
|
||||
"schema": {
|
||||
"$ref": "#\/components\/schemas\/NewPet"
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet",
|
||||
"description": "the newly created pet",
|
||||
"schema": {
|
||||
"$ref": "#\/components\/schemas\/Pet"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "petstore_client.GetPetById",
|
||||
"description": "gets a pet based on a single ID, if the user has access to the pet",
|
||||
"params": [
|
||||
{
|
||||
"name": "id",
|
||||
"description": "ID of pet to fetch",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet",
|
||||
"description": "pet response",
|
||||
"schema": {
|
||||
"$ref": "#\/components\/schemas\/Pet"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "petstore_client.DeletePetById",
|
||||
"description": "deletes a single pet based on the ID supplied",
|
||||
"params": [
|
||||
{
|
||||
"name": "id",
|
||||
"description": "ID of pet to delete",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"result": {
|
||||
"name": "pet",
|
||||
"description": "pet deleted",
|
||||
"schema": {
|
||||
"type": "null"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"components": {
|
||||
"schemas": {
|
||||
"NewPet": {
|
||||
"title": "NewPet",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"tag": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Pet": {
|
||||
"title": "Pet",
|
||||
"description": "a pet struct that represents a pet",
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "name of the pet",
|
||||
"type": "string"
|
||||
},
|
||||
"tag": {
|
||||
"description": "a tag of the pet, helps finding pet",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "unique indentifier",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user