easegress_sdk/
lib.rs

1// Copyright (c) 2017, MegaEase All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
2
3use std::collections::HashMap;
4
5use crate::marshal::marshal_string;
6
7extern crate wee_alloc;
8
9#[global_allocator]
10static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
11
12pub mod cluster;
13pub mod cookie;
14mod marshal;
15pub mod request;
16pub mod response;
17
18/// wasm_alloc is an export function for Easegress. Do not use it.
19#[no_mangle]
20pub extern "C" fn wasm_alloc(size: i32) -> i32 {
21    let buf: Vec<u8> = Vec::with_capacity(size as usize);
22    buf.as_ptr() as i32
23}
24
25/// wasm_free is an export function for Easegress. Do not use it.
26#[no_mangle]
27pub extern "C" fn wasm_free(ptr: i32) {
28    let p = ptr as *const i32;
29    let length = unsafe { std::ptr::read(p) } as usize;
30    let data = unsafe { Vec::from_raw_parts(ptr as *mut u8, length + 4, length + 4) };
31    drop(data);
32}
33
34/// Extend the ability of Easegress by implement `Program` trait.
35pub trait Program {
36    /// Easegress will call `new` when initializing the WasmHost filter. You can initialize your struct here.
37    ///
38    /// The parameter is a `HashMap<String, String>` representing `parameters` field in the spec.
39    ///
40    /// e.g. With this spec:
41    ///
42    /// ```yaml
43    /// filters:
44    /// - name: wasm
45    ///   kind: WasmHost
46    ///   parameters:
47    ///     blockRatio: "0.4"
48    ///     maxPermission: "3"
49    /// ```
50    ///
51    /// `HashMap<String, String>` contains {"blockRation": "0.4", "maxPermission": "3"}.
52    fn new(params: HashMap<String, String>) -> Self;
53
54    /// Easegress will call `run` on each request.
55    fn run(&self) -> i32 {
56        0
57    }
58}
59
60#[link(wasm_import_module = "easegress")]
61extern "C" {
62    fn host_add_tag(addr: i32);
63    fn host_log(level: i32, msg: i32);
64    fn host_get_unix_time_in_ms() -> i64;
65    fn host_rand() -> f64;
66}
67
68/// AddTag add a tag to the Request Context.
69#[no_mangle]
70pub fn add_tag(tag: String) {
71    let data = marshal_string(tag);
72    unsafe { host_add_tag(data.as_ptr() as i32) }
73}
74
75#[derive(Copy, Clone)]
76pub enum LogLevel {
77    Debug = 0,
78    Info = 1,
79    Warning = 2,
80    Error = 3,
81}
82
83/// print log in Easegress server.
84#[no_mangle]
85pub fn log(level: LogLevel, msg: String) {
86    let data = marshal_string(msg);
87    unsafe {
88        host_log(level as i32, data.as_ptr() as i32);
89    }
90    drop(data);
91}
92
93#[no_mangle]
94pub fn get_unix_time_in_ms() -> i64 {
95    unsafe { host_get_unix_time_in_ms() }
96}
97
98#[no_mangle]
99pub fn rand() -> f64 {
100    unsafe { host_rand() }
101}