1 个不稳定版本
| 0.1.0 | 2019年2月17日 |
|---|
#13 in #entrypoint
13KB
189 行
为Rust算法生成入口点
使用#[entrypoint]注释一个自由函数或类型的实现块,以生成所需的EntryPoint/DecodedEntryPoint实现。
入门指南
要将简单的apply函数设置为由算法入口点,只需在该方法上使用#[entrypoint]注释
#![feature(proc_macro)]
extern crate algorithmia;
use algorithmia::prelude::*;
#[entrypoint]
fn apply(name: String) -> Result<String, String> {
unimplemented!()
}
注意:feature(proc_macro)和一个夜间编译器是必需的,直到proc_macro_attribute稳定(可能还需要数月)。
自动JSON序列化/反序列化
要使用自定义类型作为输入和输出,只需分别实现Deserialize和Serialize。
#[derive(Deserialize)
struct Input { titles: Vec<String>, max: u32 }
#[derive(Serialize)
struct Output { titles: Vec<String> }
#[entrypoint]
fn start(input: Input) -> Result<Output, String> {
unimplemented!();
}
注意:目前这取决于特殊化以序列化非装箱输出。
预加载(高级使用)
如果你的算法有一个不随用户输入变化的预加载步骤(例如加载模型),你可以创建一个实现Default的类型,并使用该类型的某个方法作为你的入口点(#[entrypoint]注释应用于你类型的实现)。来自单个用户的连续多个API调用将只实例化该类型一次,但会多次调用apply
#[derive(Deserialize)
struct Input { titles: Vec<String>, max: u32 }
#[derive(Serialize)
struct Output { titles: Vec<String> }
struct App { model: Vec<u8> }
#[entrypoint]
impl App {
fn apply(input: Input) -> Result<Output, String> {
unimplemented!();
}
}
impl Default for App {
fn default() -> Self {
App { model: load_model() }
}
}
输入/输出类型
有效输入:
- 字符串类型(例如
&str和String) - 字节类型(例如
&[u8]和Vec<u8> - Json
&Value类型 - AlgoIo 枚举类型(用于匹配文本、json 和二进制输入)
- 实现
serde::Deserialize的任何类型(例如#[derive(Deserialize)]
有效输出(返回值的 Ok 变体):
String,Vec<u8>,Value,AlgoIo- 实现
serde::Serialize的任何类型(例如#[derive(Serialize)]
有效错误类型(返回值的 Err 变体):任何可以转换为 Box<Error> 的类型。这包括 String 以及实现 Error 特性的任何类型。
未来工作
- 在高级情况下允许指定
apply和default方法 - 更好的错误处理
- 无法将入口点附加到
struct Algo - 关于有效返回类型的断言和指导
- 无法将入口点附加到
- 添加测试
依赖关系
~4.5MB
~92K SLoC