├── .circleci └── config.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── build_image.sh ├── images ├── build │ └── 1.53 │ │ └── Dockerfile ├── init │ ├── Dockerfile │ ├── init.sh │ └── template │ │ ├── Cargo.toml │ │ ├── Dockerfile.in │ │ ├── func.init.yaml │ │ └── src │ │ └── main.rs └── runtime │ └── 1.53 │ └── Dockerfile ├── release.sh ├── release_images.sh └── src ├── coercions.rs ├── context.rs ├── errors.rs ├── function.rs ├── lib.rs ├── logging.rs ├── socket.rs └── utils.rs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | jobs: 3 | "build": 4 | docker: 5 | - auth: 6 | password: $DOCKER_PASS 7 | username: $DOCKER_USER 8 | image: circleci/rust:1.53 9 | working_directory: ~/fdk-rust 10 | steps: 11 | - checkout 12 | - run: 13 | command: | 14 | cargo build 15 | "test": 16 | docker: 17 | - auth: 18 | password: $DOCKER_PASS 19 | username: $DOCKER_USER 20 | image: circleci/rust:1.53 21 | working_directory: ~/fdk-rust 22 | steps: 23 | - checkout 24 | - run: 25 | command: | 26 | cargo test 27 | "deploy": 28 | docker: 29 | - auth: 30 | password: $DOCKER_PASS 31 | username: $DOCKER_USER 32 | image: circleci/rust:1.53 33 | working_directory: ~/fdk-rust 34 | steps: 35 | - add_ssh_keys: 36 | fingerprints: 37 | - "2c:fe:42:ac:7d:2c:ed:8e:3a:d5:22:77:8d:5e:68:87" 38 | - checkout 39 | - setup_remote_docker: 40 | docker_layer_caching: false 41 | - run: 42 | command: | 43 | cargo build 44 | - deploy: 45 | command: | 46 | if [[ "${CIRCLE_BRANCH}" == "master" && -z "${CIRCLE_PR_REPONAME}" ]]; then 47 | printenv DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin 48 | git config --global user.email "ci@fnproject.com" 49 | git config --global user.name "CI" 50 | git branch --set-upstream-to=origin/${CIRCLE_BRANCH} ${CIRCLE_BRANCH} 51 | 52 | cargo login ${FN_CARGO_TOKEN} 53 | 54 | # Build and deploy init image 55 | pushd images/init && docker build -t fnproject/rust:init . && popd && docker push fnproject/rust:init 56 | 57 | ./release.sh 58 | ./build_image.sh 1.53 59 | ./release_images.sh 60 | fi 61 | 62 | workflows: 63 | version: 2 64 | commit: 65 | jobs: 66 | - "build" 67 | - "test" 68 | - "deploy" 69 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | .idea/ 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "fdk" 4 | version = "0.2.0" 5 | authors = ["Dario Domizioli ", "Gaurav Saini "] 6 | description = "Function Development Kit for the Fn Project serverless platform" 7 | repository = "https://github.com/fnproject/fdk-rust" 8 | keywords = ["Fn", "serverless", "FaaS"] 9 | categories = ["web-programming", "development-tools"] 10 | license = "Apache-2.0" 11 | 12 | [badges] 13 | maintenance = { status = "experimental" } 14 | 15 | [dependencies] 16 | hyper = { version = "0.14", features = ["full"] } 17 | tokio = { version = "1.6", features = ["net"] } 18 | futures = "0.3" 19 | object-pool = "0.5" 20 | lazy_static = "1" 21 | url = "2" 22 | serde = "1" 23 | serde_json = "1" 24 | serde_yaml = "0.8" 25 | serde-xml-rs = "0.4" 26 | serde_plain = "0.3" 27 | serde_urlencoded = "0.7" 28 | clap = "2" 29 | thiserror = "1" 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Oracle Corporation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FDK: Fn Function Development Kit 2 | 3 | ###### Disclaimer: This FDK is experimental and is not actively maintained. It is completely functional as of July 2021, but is not supported. 4 | 5 | fdk’s current version badge 6 | 7 | The API provided hides the implementation details of the Fn platform 8 | contract and allows a user to focus on the code and easily implement 9 | function-as-a-service programs. 10 | 11 | # Usage 12 | 13 | The Fn platform offers a 14 | [command line tool](https://github.com/fnproject/fn/blob/master/README.md#quickstart) 15 | to initialize, build and deploy function projects. Follow the `fn` tool 16 | quickstart to learn the basics of the Fn platform. 17 | 18 | Boilerplate code can be generated using the following command: 19 | `fn init --init-image=fnproject/rust:init` 20 | 21 | The initializer will actually use cargo and generate a cargo binary project 22 | for the function. It is then possible to specify a dependency as usual. 23 | 24 | ```toml 25 | [dependencies] 26 | fdk = ">=0.2.0" 27 | ``` 28 | 29 | # Examples 30 | 31 | This is a simple function which greets the name provided as input. This code was generated using the above mentioned boilerplate code command. 32 | 33 | ```rust 34 | use fdk::{Function, FunctionError, RuntimeContext}; 35 | use tokio; // Tokio for handling future. 36 | 37 | #[tokio::main] 38 | async fn main() -> Result<(), FunctionError> { 39 | if let Err(e) = Function::run(|_: &mut RuntimeContext, i: String| { 40 | Ok(format!( 41 | "Hello {}!", 42 | if i.is_empty() { 43 | "world" 44 | } else { 45 | i.trim_end_matches("\n") 46 | } 47 | )) 48 | }) 49 | .await 50 | { 51 | eprintln!("{}", e); 52 | } 53 | Ok(()) 54 | } 55 | ``` 56 | -------------------------------------------------------------------------------- /build_image.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | 19 | set -xe 20 | 21 | if [ -z "$1" ];then 22 | echo "Please supply Rust version as argument to build image." >> /dev/stderr 23 | exit 2 24 | fi 25 | 26 | rustversion=$1 27 | 28 | pushd images/build/${rustversion} && docker build -t fnproject/rust:${rustversion}-dev . && popd 29 | pushd images/runtime/${rustversion} && docker build -t fnproject/rust:${rustversion} . && popd 30 | -------------------------------------------------------------------------------- /images/build/1.53/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | FROM rust:1.53-alpine3.13 18 | 19 | RUN apk add --no-cache wget curl alpine-sdk 20 | -------------------------------------------------------------------------------- /images/init/Dockerfile: -------------------------------------------------------------------------------- 1 | # docker build -t fnproject/rust:init . 2 | 3 | FROM alpine:latest 4 | COPY . . 5 | CMD ./init.sh 6 | -------------------------------------------------------------------------------- /images/init/init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | mkdir content 3 | sed s/{FUNCTION_NAME}/$FN_FUNCTION_NAME/ template/Dockerfile.in > content/Dockerfile 4 | sed s/{FUNCTION_NAME}/$FN_FUNCTION_NAME/ template/Cargo.toml > content/Cargo.toml 5 | sed s/{FUNCTION_NAME}/$FN_FUNCTION_NAME/ template/func.init.yaml > content/func.init.yaml 6 | cp -r template/src content/ 7 | tar -C content -cf init.tar . 8 | 9 | cat init.tar 10 | 11 | rm -rf content 12 | rm init.tar 13 | -------------------------------------------------------------------------------- /images/init/template/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "{FUNCTION_NAME}" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | tokio = { version = "1.6", features = ["macros", "rt-multi-thread"] } 10 | serde = { version = "1", features = ["derive"] } 11 | fdk = { version = ">=0.2.0" } 12 | -------------------------------------------------------------------------------- /images/init/template/Dockerfile.in: -------------------------------------------------------------------------------- 1 | FROM rust:1.53-alpine3.13 as builder 2 | WORKDIR /build 3 | RUN apk add alpine-sdk 4 | COPY . . 5 | RUN cargo build --release 6 | 7 | FROM alpine:3.13 8 | WORKDIR /fn 9 | COPY --from=builder /build/target/release/{FUNCTION_NAME} . 10 | CMD ["./{FUNCTION_NAME}"] 11 | -------------------------------------------------------------------------------- /images/init/template/func.init.yaml: -------------------------------------------------------------------------------- 1 | name: {FUNCTION_NAME} 2 | runtime: docker 3 | version: 0.0.0 4 | -------------------------------------------------------------------------------- /images/init/template/src/main.rs: -------------------------------------------------------------------------------- 1 | use fdk::{Function, FunctionError, RuntimeContext}; 2 | use tokio; 3 | 4 | #[tokio::main] 5 | async fn main() -> Result<(), FunctionError> { 6 | if let Err(e) = Function::run(|_: &mut RuntimeContext, i: String| { 7 | Ok(format!( 8 | "Hello {}!", 9 | if i.is_empty() { 10 | "world" 11 | } else { 12 | i.trim_end_matches("\n") 13 | } 14 | )) 15 | }) 16 | .await 17 | { 18 | eprintln!("{}", e); 19 | } 20 | Ok(()) 21 | } 22 | -------------------------------------------------------------------------------- /images/runtime/1.53/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | FROM alpine:3.13 18 | 19 | RUN apk update && apk upgrade \ 20 | && apk add ca-certificates \ 21 | && rm -rf /var/cache/apk/* 22 | 23 | RUN addgroup -g 1000 -S fn && adduser -S -u 1000 -G fn fn 24 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | set -exuo pipefail 19 | 20 | # ensure working dir is clean 21 | git status 22 | if [[ -z $(git status -s) ]] 23 | then 24 | echo "tree is clean" 25 | else 26 | echo "tree is dirty, please commit changes before running this" 27 | exit 1 28 | fi 29 | 30 | version_file="Cargo.toml" 31 | if ! grep -m1 -Eo "^version\ =\ \"[0-9]+\.[0-9]+\.[0-9]+\"$" $version_file; then 32 | echo "did not find semantic version in $version_file"; 33 | exit 1; 34 | fi 35 | perl -i -pe 's/\d+\.\d+\.\K(\d+)/$1+1/e' $version_file 36 | version=$(grep -m1 -Eo "[0-9]+\.[0-9]+\.[0-9]+" $version_file) 37 | echo "Version: $version" 38 | 39 | git add -u 40 | git commit -m "v$version release [skip ci]" 41 | git tag -f -a "v$version" -m "version v$version" 42 | git push 43 | git push --tags origin master 44 | 45 | cargo publish 46 | -------------------------------------------------------------------------------- /release_images.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | 19 | user="fnproject" 20 | image="rust" 21 | 22 | rust153="1.53" 23 | docker push ${user}/${image}:${rust153} 24 | docker push ${user}/${image}:${rust153}-dev 25 | -------------------------------------------------------------------------------- /src/coercions.rs: -------------------------------------------------------------------------------- 1 | use crate::FunctionError; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | /// ContentType represents the supported content types in the FDK. 5 | #[derive(Clone, Debug)] 6 | pub enum ContentType { 7 | JSON, 8 | YAML, 9 | XML, 10 | Plain, 11 | URLEncoded, 12 | } 13 | 14 | impl ContentType { 15 | pub fn from_str(s: &str) -> Self { 16 | match s { 17 | "application/json" => ContentType::JSON, 18 | "text/yaml" | "application/yaml" => ContentType::YAML, 19 | "text/xml" | "application/xml" => ContentType::XML, 20 | "text/plain" => ContentType::Plain, 21 | "application/x-www-form-urlencoded" => ContentType::URLEncoded, 22 | _ => ContentType::JSON, 23 | } 24 | } 25 | 26 | pub fn as_header_value(&self) -> String { 27 | match self { 28 | Self::JSON => String::from("application/json"), 29 | Self::YAML => String::from("text/yaml"), 30 | Self::XML => String::from("application/xml"), 31 | Self::Plain => String::from("text/plain"), 32 | Self::URLEncoded => String::from("application/x-www-form-urlencoded"), 33 | } 34 | } 35 | } 36 | 37 | /// An `InputCoercible` type can be generated from a `Vec`. 38 | pub trait InputCoercible: Sized { 39 | fn try_decode_plain(input: Vec) -> Result; 40 | fn try_decode_json(input: Vec) -> Result; 41 | fn try_decode_xml(input: Vec) -> Result; 42 | fn try_decode_yaml(input: Vec) -> Result; 43 | fn try_decode_urlencoded(input: Vec) -> Result; 44 | } 45 | 46 | /// An `OutputCoercible` type can be converted to a `Vec`. 47 | pub trait OutputCoercible: Sized { 48 | fn try_encode_json(self) -> Result, FunctionError>; 49 | fn try_encode_xml(self) -> Result, FunctionError>; 50 | fn try_encode_yaml(self) -> Result, FunctionError>; 51 | fn try_encode_plain(self) -> Result, FunctionError>; 52 | fn try_encode_urlencoded(self) -> Result, FunctionError>; 53 | } 54 | 55 | impl Deserialize<'de>> InputCoercible for T { 56 | fn try_decode_plain(input: Vec) -> Result { 57 | match serde_plain::from_str(&input.iter().map(|&v| v as char).collect::()) { 58 | Ok(t) => Ok(t), 59 | Err(e) => Err(FunctionError::Coercion { 60 | inner: e.to_string(), 61 | }), 62 | } 63 | } 64 | 65 | fn try_decode_json(input: Vec) -> Result { 66 | match serde_json::from_slice(input.as_slice()) { 67 | Ok(t) => Ok(t), 68 | Err(e) => Err(FunctionError::Coercion { 69 | inner: e.to_string(), 70 | }), 71 | } 72 | } 73 | 74 | fn try_decode_xml(input: Vec) -> Result { 75 | match serde_xml_rs::from_str(&input.iter().map(|&v| v as char).collect::()) { 76 | Ok(t) => Ok(t), 77 | Err(e) => Err(FunctionError::Coercion { 78 | inner: e.to_string(), 79 | }), 80 | } 81 | } 82 | 83 | fn try_decode_yaml(input: Vec) -> Result { 84 | match serde_yaml::from_slice(input.as_slice()) { 85 | Ok(t) => Ok(t), 86 | Err(e) => Err(FunctionError::Coercion { 87 | inner: e.to_string(), 88 | }), 89 | } 90 | } 91 | 92 | fn try_decode_urlencoded(input: Vec) -> Result { 93 | match serde_urlencoded::from_str(&input.iter().map(|&v| v as char).collect::()) { 94 | Ok(t) => Ok(t), 95 | Err(e) => Err(FunctionError::Coercion { 96 | inner: e.to_string(), 97 | }), 98 | } 99 | } 100 | } 101 | 102 | impl OutputCoercible for T { 103 | fn try_encode_json(self) -> Result, FunctionError> { 104 | match serde_json::to_vec(&self) { 105 | Ok(vector) => Ok(vector), 106 | Err(e) => Err(FunctionError::Coercion { 107 | inner: e.to_string(), 108 | }), 109 | } 110 | } 111 | fn try_encode_xml(self) -> Result, FunctionError> { 112 | match serde_xml_rs::to_string(&self) { 113 | Ok(vector) => Ok(vector.chars().map(|ch| ch as u8).collect()), 114 | Err(e) => Err(FunctionError::Coercion { 115 | inner: e.to_string(), 116 | }), 117 | } 118 | } 119 | fn try_encode_yaml(self) -> Result, FunctionError> { 120 | match serde_yaml::to_vec(&self) { 121 | Ok(vector) => Ok(vector), 122 | Err(e) => Err(FunctionError::Coercion { 123 | inner: e.to_string(), 124 | }), 125 | } 126 | } 127 | 128 | fn try_encode_plain(self) -> Result, FunctionError> { 129 | match serde_plain::to_string(&self) { 130 | Ok(vector) => Ok(vector.chars().map(|ch| ch as u8).collect()), 131 | Err(e) => Err(FunctionError::Coercion { 132 | inner: e.to_string(), 133 | }), 134 | } 135 | } 136 | 137 | fn try_encode_urlencoded(self) -> Result, FunctionError> { 138 | match serde_urlencoded::to_string(&self) { 139 | Ok(vector) => Ok(vector.chars().map(|ch| ch as u8).collect()), 140 | Err(e) => Err(FunctionError::Coercion { 141 | inner: e.to_string(), 142 | }), 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/context.rs: -------------------------------------------------------------------------------- 1 | use crate::coercions::ContentType; 2 | use crate::errors::FunctionError; 3 | use hyper::{ 4 | header::CONTENT_TYPE, 5 | header::{HeaderName, HeaderValue}, 6 | HeaderMap, StatusCode, 7 | }; 8 | use lazy_static::lazy_static; 9 | use std::collections::HashMap; 10 | use std::convert::TryFrom; 11 | use std::str::FromStr; 12 | use std::sync::Arc; 13 | 14 | lazy_static! { 15 | pub static ref CONFIG_FROM_ENV: Arc> = Arc::from( 16 | std::env::vars() 17 | .filter(|(_, v)| !v.as_bytes().is_empty()) 18 | .fold(HashMap::new(), |mut m, k| { 19 | m.insert(k.0, k.1); 20 | m 21 | }) 22 | ); 23 | } 24 | 25 | #[derive(Clone)] 26 | /// `RuntimeContext` contains the config and metadata of request and response. A mutable reference 27 | /// to RuntimeContext gets passed into the user function for accessing request metadata and adding 28 | /// response headers. 29 | pub struct RuntimeContext { 30 | config: Arc>, 31 | headers: HeaderMap, 32 | method: Option, 33 | content_type: ContentType, 34 | accept_type: ContentType, 35 | uri: Option, 36 | call_id: String, 37 | response_headers: HeaderMap, 38 | response_status_code: Option, 39 | } 40 | 41 | fn resolve_content_type(v: Option<&hyper::header::HeaderValue>) -> ContentType { 42 | match v { 43 | Some(value) => ContentType::from_str(value.to_str().unwrap_or("")), 44 | None => ContentType::JSON, 45 | } 46 | } 47 | 48 | fn get_accept_header_value(headers: &hyper::HeaderMap) -> Option<&HeaderValue> { 49 | if headers.get("Fn-Http-H-Accept").is_some() { 50 | headers.get("Fn-Http-H-Accept") 51 | } else if headers.get(hyper::header::ACCEPT).is_some() { 52 | headers.get(hyper::header::ACCEPT) 53 | } else { 54 | None 55 | } 56 | } 57 | 58 | impl RuntimeContext { 59 | /// from_req creates a RuntimeContext from a hyper Request reference. 60 | pub fn from_req(req: &hyper::Request) -> Self { 61 | let headers = { 62 | let fn_intent = req 63 | .headers() 64 | .get("Fn-Intent") 65 | .map(|value| value.to_str().unwrap()) 66 | .unwrap_or_else(|| ""); 67 | 68 | if fn_intent == "httprequest" { 69 | req.headers() 70 | .iter() 71 | .filter(|(k, _v)| *k == CONTENT_TYPE || k.as_str().starts_with("Fn-Http-H-")) 72 | .map(|(k, v)| (k, v.to_owned())) 73 | .fold(HeaderMap::new(), |mut m, (k, v)| { 74 | m.insert(k, v); 75 | m 76 | }) 77 | } else { 78 | req.headers().clone() 79 | } 80 | }; 81 | 82 | Self { 83 | config: CONFIG_FROM_ENV.clone(), 84 | headers: headers.clone(), 85 | method: headers 86 | .get("Fn-Http-Method") 87 | .map(|value| hyper::Method::try_from(value.to_str().unwrap()).unwrap()), 88 | content_type: resolve_content_type(req.headers().get(CONTENT_TYPE)), 89 | accept_type: resolve_content_type(get_accept_header_value(req.headers())), 90 | uri: headers 91 | .get("Fn-Http-Request-Url") 92 | .map(|value| hyper::Uri::try_from(value.to_str().unwrap()).unwrap()), 93 | call_id: headers 94 | .get("Fn-Call-Id") 95 | .map(|v| v.to_str().unwrap_or_default()) 96 | .unwrap_or_default() 97 | .to_owned(), 98 | response_headers: HeaderMap::new(), 99 | response_status_code: None, 100 | } 101 | } 102 | 103 | /// Returns the app ID 104 | pub fn app_id(&self) -> String { 105 | return (self.config.get("FN_APP_ID").unwrap_or(&String::default())).to_string(); 106 | } 107 | 108 | /// Returns the function ID 109 | pub fn function_id(&self) -> String { 110 | return (self.config.get("FN_FN_ID").unwrap_or(&String::default())).to_string(); 111 | } 112 | 113 | /// Returns the app name 114 | pub fn app_name(&self) -> String { 115 | return (self.config.get("FN_APP_NAME").unwrap_or(&String::default())).to_string(); 116 | } 117 | 118 | /// Returns the function name 119 | pub fn function_name(&self) -> String { 120 | return (self.config.get("FN_FN_NAME").unwrap_or(&String::default())).to_string(); 121 | } 122 | 123 | /// Returns the `Content-Type` header from request. This header is used to choose a deserializer for request body. 124 | pub fn content_type(&self) -> ContentType { 125 | self.content_type.clone() 126 | } 127 | 128 | /// Returns the `Accept` header from request. This header is used to choose a serializer for response body. 129 | pub fn accept_type(&self) -> ContentType { 130 | self.accept_type.clone() 131 | } 132 | 133 | /// Returns the call ID 134 | pub fn call_id(&self) -> String { 135 | self.call_id.clone() 136 | } 137 | 138 | /// Returns request headers 139 | pub fn headers(&self) -> HeaderMap { 140 | self.headers.clone() 141 | } 142 | 143 | /// Returns an `Option` based on the value of header present in headers. 144 | /// `header` returns None if the header with key is not found. 145 | pub fn header(&self, key: String) -> Option { 146 | self.headers.get(key).map(|v| { 147 | v.as_bytes() 148 | .iter() 149 | .map(|&byte| byte as char) 150 | .collect::() 151 | }) 152 | } 153 | 154 | /// Returns the config injected at the runtime from the environment variables. 155 | pub fn config(&self) -> &HashMap { 156 | &self.config 157 | } 158 | 159 | /// Adds a custom header to the response. 160 | /// 161 | /// # Examples 162 | /// 163 | /// ```rust,ignore 164 | /// ctx.add_response_header("X-COOLNESS-METER-SAYS", "OVER-9000") 165 | /// ``` 166 | pub fn add_response_header(&mut self, key: String, value: String) { 167 | self.response_headers.insert( 168 | HeaderName::from_str(key.as_str()).unwrap(), 169 | HeaderValue::from_str(value.as_str()).unwrap(), 170 | ); 171 | } 172 | 173 | /// Helper to return the response headers 174 | pub fn response_headers(&self) -> HeaderMap { 175 | self.response_headers.clone() 176 | } 177 | 178 | /// Sets the status code in the response headers under Fn-Http-Status key. 179 | /// Default value is 200. 180 | pub fn set_status_code(&mut self, status: u16) -> Result<(), FunctionError> { 181 | self.response_status_code = match StatusCode::from_u16(status) { 182 | Ok(v) => Some(v), 183 | Err(_) => { 184 | return Err(FunctionError::InvalidInput { 185 | inner: "Invalid http code added".into(), 186 | }) 187 | } 188 | }; 189 | Ok(()) 190 | } 191 | 192 | /// Helper function to return status code set by user. 193 | pub fn get_status_code(&self) -> Option { 194 | self.response_status_code 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | use hyper::{Body, Response}; 2 | 3 | use crate::utils::{ 4 | make_header_map_with_single_value, success_or_recoverable_error, unrecoverable_error, 5 | }; 6 | use thiserror::Error; 7 | 8 | #[derive(Error, Debug)] 9 | pub enum FunctionError { 10 | #[error("Invalid input: {inner:?}")] 11 | InvalidInput { inner: String }, 12 | 13 | #[error("Bad request")] 14 | BadRequest, 15 | 16 | #[error("Initialization failed: {inner:?}")] 17 | Initialization { inner: String }, 18 | 19 | #[error("Coercion failed: {inner:?}")] 20 | Coercion { inner: String }, 21 | 22 | #[error("IO Error: {inner:?}")] 23 | IO { inner: String }, 24 | 25 | #[error("Server error: {inner:?}")] 26 | Server { inner: String }, 27 | 28 | #[error("Internal system error: {inner:?}")] 29 | System { inner: String }, 30 | 31 | #[error("User error: {inner:?}")] 32 | User { inner: String }, 33 | } 34 | 35 | impl FunctionError { 36 | pub fn is_user_error(&self) -> bool { 37 | matches!( 38 | self, 39 | Self::InvalidInput { .. } 40 | | Self::BadRequest 41 | | Self::Coercion { .. } 42 | | Self::User { .. } 43 | ) 44 | } 45 | 46 | pub fn new_user_error(error: String) -> Self { 47 | Self::User { inner: error } 48 | } 49 | } 50 | 51 | impl From for hyper::Response { 52 | fn from(e: FunctionError) -> hyper::Response { 53 | if e.is_user_error() { 54 | client_error(format!("{}", e)) 55 | } else { 56 | server_error(format!("{}", e)) 57 | } 58 | } 59 | } 60 | 61 | impl From for FunctionError { 62 | fn from(e: std::io::Error) -> Self { 63 | Self::IO { 64 | inner: e.to_string(), 65 | } 66 | } 67 | } 68 | 69 | impl From for FunctionError { 70 | fn from(e: std::env::VarError) -> Self { 71 | Self::Initialization { 72 | inner: e.to_string(), 73 | } 74 | } 75 | } 76 | 77 | impl From for FunctionError { 78 | fn from(e: url::ParseError) -> Self { 79 | Self::Initialization { 80 | inner: format!("Could not parse the URL: {}", e.to_string()), 81 | } 82 | } 83 | } 84 | 85 | impl From for FunctionError { 86 | fn from(e: hyper::Error) -> Self { 87 | Self::Server { 88 | inner: e.to_string(), 89 | } 90 | } 91 | } 92 | 93 | /// A utility function that produces a client error response from a type that 94 | /// can be converted to a vector of bytes. 95 | pub fn client_error(data: T) -> Response 96 | where 97 | T: Into>, 98 | { 99 | let bytes: Vec = data.into(); 100 | let content_length = bytes.len(); 101 | success_or_recoverable_error( 102 | hyper::StatusCode::BAD_GATEWAY, 103 | Option::from(Body::from(bytes)), 104 | Option::from(make_header_map_with_single_value( 105 | hyper::header::CONTENT_LENGTH, 106 | content_length.into(), 107 | )), 108 | ) 109 | } 110 | 111 | /// A utility function that produces a server error response from a type that 112 | /// can be converted to a vector of bytes. 113 | pub fn server_error(data: T) -> Response 114 | where 115 | T: Into>, 116 | { 117 | let bytes: Vec = data.into(); 118 | let content_length = bytes.len(); 119 | unrecoverable_error( 120 | hyper::StatusCode::INTERNAL_SERVER_ERROR, 121 | Option::from(Body::from(bytes)), 122 | Option::from(make_header_map_with_single_value( 123 | hyper::header::CONTENT_LENGTH, 124 | content_length.into(), 125 | )), 126 | ) 127 | } 128 | -------------------------------------------------------------------------------- /src/function.rs: -------------------------------------------------------------------------------- 1 | use hyper::{Body, Request}; 2 | use lazy_static::lazy_static; 3 | use object_pool::Pool; 4 | use std::io::Write; 5 | 6 | use crate::coercions::{ContentType, InputCoercible, OutputCoercible}; 7 | use crate::context::RuntimeContext; 8 | use crate::errors::FunctionError; 9 | use crate::socket::UDS; 10 | use crate::utils::success_or_recoverable_error; 11 | 12 | pub type Result = core::result::Result; 13 | 14 | lazy_static! { 15 | static ref POOL: Pool> = Pool::new(1024, || Vec::with_capacity(4096)); 16 | } 17 | 18 | /// Function is the first class primitive provided by FDK to run functions on Oracle Cloud Functions and FnProject. 19 | pub struct Function; 20 | 21 | impl Function { 22 | /// `run` accepts a function from the user. `run` is an async function and returns a future which should be awaited to accept 23 | /// user requests and execute passed function on the given input. 24 | /// 25 | /// # Examples 26 | /// 27 | /// ```rust,ignore 28 | /// let function = Function::new(|_: &mut fdk::RuntimeContext, i: i32| -> Result { 29 | /// Ok(i*i) 30 | /// }); 31 | /// if let Err(e) = function.await { 32 | /// eprintln!("{}", e); 33 | /// } 34 | /// ``` 35 | pub async fn run(function: F) -> Result<()> 36 | where 37 | T: InputCoercible + 'static, 38 | S: OutputCoercible + 'static, 39 | F: Fn(&mut RuntimeContext, T) -> Result + Send + Sync + 'static, 40 | { 41 | Self::run_inner(std::sync::Arc::new(function)).await 42 | } 43 | 44 | async fn run_inner(function: std::sync::Arc) -> Result<()> 45 | where 46 | T: InputCoercible + 'static, 47 | S: OutputCoercible + 'static, 48 | F: Fn(&mut RuntimeContext, T) -> Result + Send + Sync + 'static, 49 | { 50 | let socket = match UDS::new() { 51 | Ok(s) => s, 52 | Err(e) => return Err(e), 53 | }; 54 | 55 | let svc = hyper::service::make_service_fn(|_| { 56 | let function = function.clone(); 57 | async move { 58 | Ok::<_, FunctionError>(hyper::service::service_fn(move |req: Request| { 59 | let function = function.clone(); 60 | async move { 61 | crate::logging::start_logging(req.headers()); 62 | 63 | let mut ctx = RuntimeContext::from_req(&req); 64 | 65 | // We don't need buffer to live outside of the block we decode the request body 66 | let arg = { 67 | let mut buffer = match POOL.try_pull() { 68 | Some(buf) => buf, 69 | None => { 70 | return Ok(FunctionError::System { 71 | inner: "Failed to allocate memory".into(), 72 | } 73 | .into()); 74 | } 75 | }; 76 | let _ = buffer.write( 77 | match hyper::body::to_bytes(req.into_body()).await { 78 | Ok(data) => data.to_vec(), 79 | Err(e) => { 80 | return Ok(FunctionError::IO { 81 | inner: format!("Failed to read request body: {}", e), 82 | } 83 | .into()); 84 | } 85 | } 86 | .as_ref(), 87 | ); 88 | 89 | let decoded_arg_result = decode_body(ctx.content_type(), &buffer); 90 | 91 | buffer.clear(); 92 | 93 | let decoded_arg = match decoded_arg_result { 94 | Ok(v) => v, 95 | Err(e) => { 96 | return Ok(FunctionError::Coercion { 97 | inner: format!( 98 | "Error while deserializing request body: {}", 99 | e 100 | ), 101 | } 102 | .into()) 103 | } 104 | }; 105 | 106 | decoded_arg 107 | }; 108 | 109 | let output_format = ctx.accept_type(); 110 | 111 | let output = match function(&mut ctx, arg) { 112 | Ok(out) => out, 113 | Err(e) => match e { 114 | FunctionError::User { .. } => return Ok(e.into()), 115 | _ => { 116 | return Ok(FunctionError::InvalidInput { 117 | inner: format!("Error executing user function: {}", e), 118 | } 119 | .into()) 120 | } 121 | }, 122 | }; 123 | 124 | let response_body = match encode_body(&output_format, output) { 125 | Ok(body) => body, 126 | Err(e) => { 127 | return Ok(FunctionError::Coercion { 128 | inner: format!("Error while serializing response body: {}", e), 129 | } 130 | .into()) 131 | } 132 | }; 133 | 134 | let response_content_type = output_format.as_header_value(); 135 | 136 | ctx.add_response_header( 137 | hyper::header::CONTENT_TYPE.as_str().to_owned(), 138 | response_content_type, 139 | ); 140 | 141 | Ok::<_, FunctionError>(success_or_recoverable_error( 142 | ctx.get_status_code().unwrap_or(hyper::StatusCode::OK), 143 | Option::from(Body::from(response_body)), 144 | Option::from(ctx.response_headers()), 145 | )) 146 | } 147 | })) 148 | } 149 | }); 150 | 151 | let _ = hyper::server::Server::builder(socket).serve(svc).await?; 152 | 153 | Ok(()) 154 | } 155 | } 156 | 157 | fn encode_body(content_type: &ContentType, s: S) -> Result> { 158 | match content_type { 159 | ContentType::JSON => S::try_encode_json(s), 160 | ContentType::YAML => S::try_encode_yaml(s), 161 | ContentType::XML => S::try_encode_xml(s), 162 | ContentType::Plain => S::try_encode_plain(s), 163 | ContentType::URLEncoded => S::try_encode_urlencoded(s), 164 | } 165 | } 166 | 167 | fn decode_body( 168 | content_type: ContentType, 169 | buffer: &object_pool::Reusable>, 170 | ) -> Result { 171 | match content_type { 172 | ContentType::JSON => T::try_decode_json(buffer.to_vec()), 173 | ContentType::YAML => T::try_decode_yaml(buffer.to_vec()), 174 | ContentType::XML => T::try_decode_xml(buffer.to_vec()), 175 | ContentType::Plain => T::try_decode_plain(buffer.to_vec()), 176 | ContentType::URLEncoded => T::try_decode_urlencoded(buffer.to_vec()), 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # FDK: Fn Function Development Kit 2 | //! 3 | //! This crate implements a Function Development Kit for the 4 | //! [Fn Project](http://www.fnproject.io) serverless platform. 5 | //! 6 | //! The API provided hides the implementation details of the Fn platform 7 | //! contract and allows a user to focus on the code and easily implement 8 | //! function-as-a-service programs. 9 | //! 10 | //! # Usage 11 | //! 12 | //! The Fn platform offers a 13 | //! [command line tool](https://github.com/fnproject/fn/blob/master/README.md#quickstart) 14 | //! to initialize, build and deploy function projects. Follow the `fn` tool 15 | //! quickstart to learn the basics of the Fn platform. 16 | //! 17 | //! The initializer will actually use cargo and generate a cargo binary project 18 | //! for the function. It is then possible to specify a dependency as usual. 19 | //! 20 | //! ```toml 21 | //! [dependencies] 22 | //! fdk = ">=0.2.0" 23 | //! ``` 24 | //! 25 | //! # Examples 26 | //! 27 | //! This is a simple function which greets the name provided as input. 28 | //! 29 | //! ```rust,ignore 30 | //! use fdk::{Function, FunctionError, RuntimeContext, Result}; 31 | //! use tokio; // Tokio for handling future. 32 | //! 33 | //! #[tokio::main] 34 | //! async fn main() -> Result<()> { 35 | //! if let Err(e) = Function::run(|_: &mut RuntimeContext, i: String| { 36 | //! Ok(format!( 37 | //! "Hello {}!", 38 | //! if i.is_empty() { 39 | //! "world" 40 | //! } else { 41 | //! i.trim_end_matches("\n") 42 | //! } 43 | //! )) 44 | //! }) 45 | //! .await 46 | //! { 47 | //! eprintln!("{}", e); 48 | //! } 49 | //! Ok(()) 50 | //! } 51 | //! ``` 52 | 53 | #![allow(clippy::upper_case_acronyms)] 54 | extern crate clap; 55 | extern crate futures; 56 | extern crate hyper; 57 | extern crate lazy_static; 58 | extern crate object_pool; 59 | extern crate serde_json; 60 | extern crate serde_plain; 61 | extern crate serde_urlencoded; 62 | extern crate serde_xml_rs; 63 | extern crate serde_yaml; 64 | extern crate thiserror; 65 | extern crate tokio; 66 | extern crate url; 67 | 68 | mod coercions; 69 | mod context; 70 | mod errors; 71 | mod function; 72 | mod logging; 73 | mod socket; 74 | mod utils; 75 | 76 | pub use coercions::{InputCoercible, OutputCoercible}; 77 | pub use context::RuntimeContext; 78 | pub use errors::FunctionError; 79 | pub use function::{Function, Result}; 80 | -------------------------------------------------------------------------------- /src/logging.rs: -------------------------------------------------------------------------------- 1 | use crate::context; 2 | use hyper::HeaderMap; 3 | 4 | /// start_logging enables logging for a user request. 5 | pub fn start_logging(headers: &HeaderMap) { 6 | let config = context::CONFIG_FROM_ENV.clone(); 7 | 8 | let framer = match config.get("FN_LOGFRAME_NAME") { 9 | Some(v) => v, 10 | None => return, 11 | }; 12 | 13 | let value_src = match config.get("FN_LOGFRAME_HDR") { 14 | Some(v) => v, 15 | None => return, 16 | }; 17 | 18 | if let Some(v) = headers.get(value_src) { 19 | if !v.is_empty() { 20 | println!("\n{}={}", framer, v.to_str().unwrap()); 21 | eprintln!("\n{}={}", framer, v.to_str().unwrap()); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/socket.rs: -------------------------------------------------------------------------------- 1 | use crate::FunctionError; 2 | use hyper::server::accept::Accept; 3 | use std::fs; 4 | use std::os::unix::fs::{symlink, PermissionsExt}; 5 | use std::path::Path; 6 | use std::pin::Pin; 7 | use std::task::{Context, Poll}; 8 | use tokio::net::UnixListener; 9 | use url::Url; 10 | 11 | /// UDS is a wrapper over a UnixListener. It is a `hyper::server::accept::Accept` and can be used with hyper. 12 | pub struct UDS(UnixListener); 13 | 14 | impl UDS { 15 | pub fn new() -> Result { 16 | let fn_format = std::env::var("FN_FORMAT").unwrap_or_default(); 17 | if fn_format.as_str() != "http-stream" && fn_format.as_str() != "" { 18 | return Err(FunctionError::Initialization { 19 | inner: format!("Unsupported FN_FORMAT specified: {}", fn_format), 20 | }); 21 | }; 22 | 23 | let fn_listener = std::env::var("FN_LISTENER")?; 24 | if fn_listener.is_empty() { 25 | return Err(FunctionError::Initialization { 26 | inner: "FN_LISTENER not found in env".to_owned(), 27 | }); 28 | }; 29 | 30 | let socket_url = Url::parse(&fn_listener)?; 31 | 32 | if socket_url.scheme() != "unix" || socket_url.path() == "" { 33 | return Err(FunctionError::Initialization { 34 | inner: format!("Malformed FN_LISTENER specified: {}", socket_url.as_str()), 35 | }); 36 | } 37 | 38 | let socket_file_path = Path::new(socket_url.path()); 39 | let phony_socket_file_path = Path::new(socket_file_path.parent().unwrap()).join(format!( 40 | "phony{}", 41 | socket_file_path.file_name().unwrap().to_str().unwrap() 42 | )); 43 | 44 | // Try to clean up old sockets 45 | { 46 | let _ = fs::remove_file(&socket_file_path); 47 | let _ = fs::remove_file(&phony_socket_file_path); 48 | } 49 | 50 | let listener = UnixListener::bind(&phony_socket_file_path.to_str().unwrap())?; 51 | 52 | let socket = UDS(listener); 53 | // Set permissions to 0o666 and set symlink 54 | { 55 | let _ = std::fs::set_permissions( 56 | &phony_socket_file_path, 57 | fs::Permissions::from_mode(0o666), 58 | )?; 59 | 60 | let _ = symlink( 61 | &phony_socket_file_path 62 | .file_name() 63 | .unwrap() 64 | .to_str() 65 | .unwrap(), 66 | socket_file_path, 67 | )?; 68 | } 69 | Ok(socket) 70 | } 71 | } 72 | 73 | impl Accept for UDS { 74 | type Conn = tokio::net::UnixStream; 75 | type Error = FunctionError; 76 | 77 | fn poll_accept( 78 | self: Pin<&mut Self>, 79 | cx: &mut Context<'_>, 80 | ) -> Poll>> { 81 | match self.0.poll_accept(cx) { 82 | Poll::Pending => Poll::Pending, 83 | Poll::Ready(Ok((socket, _address))) => Poll::Ready(Some(Ok(socket))), 84 | Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err.into()))), 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use clap::crate_version; 2 | use hyper::{ 3 | header::{HeaderName, HeaderValue}, 4 | Body, HeaderMap, Response, StatusCode, 5 | }; 6 | use std::str::FromStr; 7 | 8 | pub fn make_header_map_with_single_value(key: HeaderName, value: HeaderValue) -> HeaderMap { 9 | let mut header_map = HeaderMap::new(); 10 | header_map.insert(key, value); 11 | header_map 12 | } 13 | 14 | fn generic_response(status: StatusCode, body: Option, headers: HeaderMap) -> Response { 15 | let mut builder = Response::builder().status(status); 16 | { 17 | let mut headers = headers; 18 | headers.insert( 19 | "Fn-Fdk-Version", 20 | HeaderValue::from_str(&format!("fdk-rust/{}", crate_version!())).unwrap(), 21 | ); 22 | let resp_headers = builder.headers_mut().unwrap(); 23 | *resp_headers = headers; 24 | } 25 | 26 | let mut response_body = Body::empty(); 27 | if let Some(body) = body { 28 | response_body = body; 29 | } 30 | builder.body(response_body).unwrap() 31 | } 32 | 33 | fn add_status_header(header: Option, status: StatusCode) -> HeaderMap { 34 | header 35 | .map(|mut hdrs| { 36 | hdrs.insert( 37 | HeaderName::from_str("Fn-Http-Status").unwrap(), 38 | status.as_u16().into(), 39 | ); 40 | hdrs 41 | }) 42 | .unwrap_or_else(|| { 43 | make_header_map_with_single_value( 44 | HeaderName::from_str("Fn-Http-Status").unwrap(), 45 | status.as_u16().into(), 46 | ) 47 | }) 48 | } 49 | 50 | pub fn success_or_recoverable_error( 51 | status: StatusCode, 52 | body: Option, 53 | headers: Option, 54 | ) -> Response { 55 | let response_headers = add_status_header(headers, status); 56 | generic_response(StatusCode::OK, body, response_headers) 57 | } 58 | 59 | pub fn unrecoverable_error( 60 | status: StatusCode, 61 | body: Option, 62 | headers: Option, 63 | ) -> Response { 64 | let response_headers = add_status_header(headers, status); 65 | generic_response(StatusCode::BAD_GATEWAY, body, response_headers) 66 | } 67 | --------------------------------------------------------------------------------