main.go Documentation

Official TypeScript developer resources and documentation for fnproject/main.go. Verified technical context for AI.

0 stars TypeScript TypeScript 1 file ยท ~4,865 tokens
RAW Doc

1. Project Overview & Quickstart (fnproject/main.go)

main.go

Open-source repository fnproject/main.go

Repository Details

Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.

2. Official Technical Reference & Guides (fnproject/docs)

File: README.md

Project Documentation

Quickstart  |  Tutorials  |  Docs  |  API

Fn is an event-driven, open source, Functions-as-a-Service (FaaS) compute platform that you can run anywhere.

Getting Started


File: cli/how-to/README.md

CLI How-to

Manage Fn Servers
Create and Run Functions


File: cli/ref/README.md

Fn Command Reference

fn build
fn bump
fn config
fn create
fn create app
fn create context
fn create function
fn create trigger
fn delete
fn deploy
fn get
fn get config
fn help
fn init
fn inspect
fn invoke
fn list
fn list apps
fn list config
fn list contexts
fn list triggers
fn migrate
fn push
fn start
fn stop
fn unset
fn update
fn update app
fn update context
fn update function
fn update server
fn update trigger
fn use
fn version

version: 0.5.91


File: cli/README.md

CLI Guide

**Table of Contents** [CLI Source Code](#cli-source-code) [Fn Command Reference](#fn-command-reference) [Fn CLI How-to Guides](#fn-cli-how-to-guides)

CLI Source Code

Fn Command Reference

fn build
fn bump
fn config
fn create
fn create app
fn create context
fn create function
fn create trigger
fn delete
fn deploy
fn get
fn get config
fn help
fn init
fn inspect
fn invoke
fn list
fn list apps
fn list config
fn list contexts
fn list triggers
fn migrate
fn push
fn start
fn stop
fn unset
fn update
fn update app
fn update context
fn update function
fn update server
fn update trigger
fn use
fn version

version: 0.5.96

[Fn CLI How-to Guides](how-to/README.md)

Deploy Apps with Fn


File: community/README.md

Project Community

Welcome!

Before proceeding, please review the Fn Code of Conduct.

Welcome to the Fn Project Community! You will find all the resources you need here to join our community, whether as a user, contributor, speaker, partner, or just observer.

Bi-Weekly Fn Community Call

The Fn Project community calls take place every other Tuesday and are open to anyone. You can find the date of the next call, dial-in information, and past meeting notes here: http://comcall.fnproject.io

For Contributors

If you are working on the Fn Project, want to work on it or are creating extensions, start with our contributing guidelines page.

Workstreams

This list is unordered and simply a placeholder to start the conversation. May move to a GitHub Project per issue 1070)

  1. Fn Server core performance work

  2. Terraform scripts for full "prod" deployment on multiple clouds

  3. Tighter Kubernetes integration

    • Using CRD's to manage funcs
    • Accessing secrets
    • Using pods to schedule work
    • Possible integrations with Knative build, serve, or eventing
  4. Additional triggers

    • Kafka (in progress)
    • OracleDB
    • MySQL
    • Scheduled (CRON like)
  5. Update and Fix UI (might be complete rewrite)

  6. Fn Flow

To start using the Fn Project, visit our main repo here: https://github.com/fnproject/fn


File: examples/README.md

Example

Here are examples that show how to implement and use Fn.

[FDK-Java Examples](../fdks/fdk-java/README.md)


File: fdks/fdk-ruby/README.md

Function Development Kit for Ruby

The Function Development Kit for Ruby (FDK for Ruby) provides a Ruby framework for developing functions for us with Fn.

Function Handler

To use this FDK, you simply need to require this gem.

ruby
require 'fdk`

Then create a function with with the following syntax:

ruby
def myfunc(context, input)
    # Do some work here
    return output
end
  • context - provides runtime information for your function, such as configuration values, headers, etc.
  • input โ€“ This parameter is a string containing body of the request.
  • output - is where you can return data back to the caller. Whatever you return will be sent back to the caller.
    • Default output format should be in JSON, as Content-Type header will be application/json by default. You can be more flexible if you create and return
      an FDK::Response object instead of a string.

Then simply pass that function to the FDK:

ruby
FDK.handle(myfunction)

Full Example

ruby
require 'fdk'

def myfunction(context:, input:)
  input_value = input.respond_to?(:fetch) ? input.fetch('name') : input
  name = input_value.to_s.strip.empty? ? 'World' : input_value
  { message: "Hello #{name}!" }
end

FDK.handle(function: :myfunction)

Running the example that is in the root directory of this repo

sh
$ echo '{"name":"coolio"}' | fn run
{"message":"Hello coolio!"}

You can also specify the format (the default is JSON)

sh
$ echo '{"name":"coolio"}' | fn run --format json
{"message":"Hello coolio!"}

If you want to just pass plain text to the function, specify a format of default:

sh
$ echo 'coolio' | fn run --format default
{"message":"Hello coolio!"}

Deploy:

sh
fn deploy --app myapp --local && echo '{"name":"coolio"}' | fn call myapp /fdk-ruby

Change to hot:

Update func.yaml: format: json

sh
fn deploy --app myapp --local && echo '{"name":"coolio"}' | fn call myapp /fdk-ruby

Compare cold and hot

Run

sh
ruby loop.rb

File: fdks/fdk-python/README.md

FN development kit for Python

Purpose of this library to provide simple interface to parse HTTP 1.1 requests.

Following examples are showing how to use API of this library to work with streaming HTTP requests from Fn service.

Handling JSON Functions

A main loop is supplied that can repeatedly call a user function with a series of HTTP requests.
In order to utilise this, you can write your func.py as follows:

py
import json
import io

from fdk import response


def handler(ctx, data: io.BytesIO=None):
    name = "World"
    try:
        body = json.loads(data.getvalue())
        name = body.get("name")
    except (Exception, ValueError) as ex:
        print(str(ex))

    return response.Response(
        ctx, response_data=json.dumps(
            {"message": "Hello {0}".format(name)}), 
        headers={"Content-Type": "application/json"}
    )

File: fdks/fdk-node/README.md

Fn Function Development Kit for Node.js

This Function Development Kit makes it easy to deploy Node.js functions to Fn.

Creating a Node Function

Writing a Node.js function is simply a matter of writing a handler function
that you pass to the FDK to invoke each time your function is called.

Start by creating a node function with fn init and installing the FDK:

sh
fn init --runtime node nodefunc
cd nodefunc

This creates a simple hello world function in func.js:

javascript
var fdk = require('@fnproject/fdk');

fdk.handle(function(input) {
  var name = 'World';
  if (input.name) {
    name = input.name;
  }
  response = {'message': 'Hello ' + name}
  return response
})

The handler function takes the string input that is sent to the function
and returns a response string. Using the FDK you don't have to worry about reading
input from standard input and writing to standard output to return your response.
The FDK let's you focus on your function logic and not the mechanics.

Now run it!

sh
fn run

Now you have a basic running Node function that you can modify and add what you want.

From this point on, it's the same as any other function in any language.
deploy the function:

sh
fn deploy --app fnfdk --local

Once deployed, you and invoke the function:

sh
echo -n "Tom" | fn call fdkdemo /hello

or

sh
curl -d "Tom" http://localhost:8080/r/fdkdemo/hello

In both cases you'll get the response:

sh
Hello Tom from Node!

Function Context

Function invocation context details are available through an optional function argument.
To receive a context object, simply add a second argument to your handler function.
in the following example the call_id is obtained from the context and included in
the response message:

javascript
var fdk = require('@fnproject/fdk');

fdk.handle(function(input, ctx) {
  var name = 'World';
  if (input) {
    name = input;
  }
  return 'Hello ' + name + ' from Node call ' + ctx.callId + '!';
})

In the case of default format functions the context give you access to all environment variables
including those defined through function or app config as well as those automatically provided
by Fn like app_name, path, memory, etc.

Asynchronous function responses

You return an asynchronous response from a function by returning a Javascript Promise from the function body:

javascript
var fdk = require('@fnproject/fdk');

fdk.handle(function(input, ctx) {
  return new Promise((resolve, reject) => {
     setTimeout(() => resolve("Hello"), 1000);
  });
})

Handling non-json input and output

By default the FDK will convert input with a content-type matching application/json into a JSON object as the function input, if the incoming content type is different from application/json then the input will be the raw string value of the input. In both cases, the raw (string) version of the input is also available in ctx.body.

Likewise by default the output of a function will be treated as a JSON object and converted using JSON.stringify - you can change this behaviour by setting the content type of the response in the context using ctx.responseContentType='application/text-plain'. Changing the content type to non-json will result in the output being treated as a string.

Using HTTP headers and setting HTTP status codes

You can read http headers passed into a function invocation using ctx.protocol.header(key), this returns the first header value of the header matching key (after canonicalization) and ctx.protocol.headers which returns an object containing all headers.

javascript
var fdk = require('@fnproject/fdk');

fdk.handle(function(input, ctx) {
  console.log("Authorization header:" , ctx.protocol.header("Authorization"))
  console.log( ctx.protocol.headers) // prints e.g. { "Content-Type": ["application/json"],"Accept":["application/json","text/plain"] } 
})

Outbound headers and the HTTP status code can be modified when the function uses the json request format.

To update the outbound status-code set ctx.protocol.statusCode. To modify outbound headers use ctx.protocol.setHeader(k,v) or ctx.protocol.addHeader(k,v) which set (overwriting existing headers) or add (preserving existing headers) headers to the response respectively.

javascript
var fdk = require('@fnproject/fdk');

fdk.handle(function(input, ctx) {
   ctx.protocol.setHeader("Location", "http://example.com")
   ctx.protocol.statusCode = 302
})

Fn and Node.js Dependencies

Fn handles Node.js dependencies in the following way:

  • If a package.json is present without a node_modules directory, an Fn build runs an npm install within the build process and installs your dependencies.
  • If the node_modules is present, Fn assumes you have provided the dependencies yourself and no installation is performed.

File: fdks/fdk-java/examples/string-reverse/README.md

Example Java Function: String Reverse

This example provides an HTTP trigger endpoint for reversing strings.

bash
$ curl -d "Hello World" http://localhost:8080/t/string-reverse-app/string-reverse
dlroW olleH

Demonstrated FDK features

This example uses none of the Fn FDK for Java features, in fact it doesn't
have any dependency on the FDK for Java. It is just plain old Java code.

Step by step

Ensure you have the Fn server running to host your function and provide the HTTP endpoint that invokes it:

(1) Start the server

sh
$ fn start

(2) Create an app for the function

sh
$ fn create app string-reverse-app

(3) Deploy the function to your app from the string-reverse directory.

sh
fn deploy --app string-reverse-app --local

(4) Invoke the function and reverse the string.

sh
echo "Hello World" | fn invoke string-reverse-app string-reverse
dlroW olleH

(5) Invoke the function using curl and a trigger to reverse a string.

bash
$ curl -d "Hello World" http://localhost:8080/t/string-reverse-app/string-reverse
dlroW olleH

Code walkthrough

The entrypoint to the function is specified in func.yaml in the cmd key.
It is set to com.example.fn.StringReverse::reverse. The whole class
StringReverse is shown below:

java
package com.example.fn;

public class StringReverse {
    public String reverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }
}

As you can see, this is plain Java with no references to the Fn API. The
Fn FDK for Java handles the marshalling of the HTTP body into the str
parameter as well as the marshalling of the returned reversed string into the HTTP
response body (see Data Binding for more
information on how marshalling is performed).