### Docker Compose Quick Start Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This snippet shows the simple commands to get SlimFaas running locally using Docker Compose. It involves cloning the repository and running `docker-compose up`. After the services are up, you can access functions via a specific URL. ```bash git clone https://github.com/AxaFrance/slimfaas.git cd slimfaas docker-compose up ``` -------------------------------- ### Kubernetes Quick Start Deployment Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This snippet demonstrates the steps to deploy SlimFaas and sample functions on a Kubernetes cluster. It includes cloning the repository, applying YAML configurations for the service account, deployment, exposing the service (NodePort or Ingress), deploying sample functions, and setting up MySQL. It also shows how to run a demo webapp. ```bash git clone https://github.com/AxaFrance/slimfaas.git cd slimfaas/demo # Deploy SlimFaas (StatefulSet) and related ServiceAccount kubectl apply -f service-account-slimfaas.yml kubectl apply -f deployment-slimfaas.yml # Expose SlimFaas Service as NodePort or Ingress kubectl apply -f slimfaas-nodeport.yml # Alternatively: # kubectl apply -f slimfaas-ingress.yml # Deploy three sample Fibonacci functions kubectl apply -f deployment-functions.yml # Deploy MySQL (used by the Fibonacci functions) kubectl apply -f deployment-mysql.yml # (Optional) Run a single-page demo webapp on http://localhost:8000 docker run -d -p 8000:8000 --rm axaguildev/fibonacci-webapp:latest ``` -------------------------------- ### Accessing SlimFaas via Docker Compose Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This section details how to access a deployed function when using the Docker Compose setup. It specifies the base URL and the path to a sample function. ```APIDOC Accessing Functions (Docker Compose): GET http://slimfaas/function/fibonacci/hello/guillaume ``` -------------------------------- ### Testing SlimFaas Functions (Kubernetes) Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This section provides examples of how to test synchronous and asynchronous calls to deployed SlimFaas functions. It also includes how to wake up a specific function and list all deployed functions. The examples assume the SlimFaas service is exposed via NodePort on port 30021. ```APIDOC SlimFaas API Endpoints: Synchronous Function Calls: GET http://localhost:30021/function///... - Example: GET http://localhost:30021/function/fibonacci1/hello/guillaume → HTTP 200 (OK) - Example: GET http://localhost:30021/function/fibonacci4/hello/julie → HTTP 404 (Not Found) Asynchronous Function Calls: GET http://localhost:30021/async-function///... - Example: GET http://localhost:30021/async-function/fibonacci1/hello/guillaume → HTTP 202 (Accepted) - Example: GET http://localhost:30021/async-function/fibonacci4/hello/julie → HTTP 404 (Not Found) Wake Up a Function: GET http://localhost:30021/wake-function/ - Example: GET http://localhost:30021/wake-function/fibonacci1 → HTTP 204 (No Content) - Example: GET http://localhost:30021/wake-function/fibonacci4 → HTTP 204 (No Content) List All Functions: GET http://localhost:30021/status-functions - Returns a JSON array with status information for each function. - Example Response: [ {"NumberReady":1,"numberRequested":1,"PodType":"Deployment","Visibility":"Public","Name":"fibonacci1"}, {"NumberReady":1,"numberRequested":1,"PodType":"Deployment","Visibility":"Public","Name":"fibonacci2"}, {"NumberReady":1,"numberRequested":1,"PodType":"Deployment","Visibility":"Public","Name":"fibonacci3"}, {"NumberReady":2,"numberRequested":2,"PodType":"Deployment","Visibility":"Private","Name":"fibonacci4"} ] ``` -------------------------------- ### Local Demo Setup Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Instructions to clone the slimfaas repository, navigate to the SlimFaasPlanetSaver directory, install dependencies, and run the development server to view the demo. ```bash git clone https://github.com/SlimPlanet/slimfaas.git cd slimfaas/src/SlimFaasPlanetSaver npm install npm run dev ``` -------------------------------- ### React with Vite using Babel Source: https://github.com/slimplanet/slimfaas/blob/main/src/FibonacciReact/README.md This snippet demonstrates the setup for a React project using Vite with the official Babel plugin for Fast Refresh. It requires installing the plugin and configuring Vite. ```javascript import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' export default defineConfig({ plugins: [react()], }) ``` -------------------------------- ### SlimFaas StatefulSet and Service Deployment Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This YAML defines a Kubernetes StatefulSet for deploying SlimFaas with 3 replicas and exposes it via a Service. It specifies the container image, ports for SlimFaas and SlimData, and labels for selection. ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: name: slimfaas namespace: slimfaas-demo spec: replicas: 3 selector: matchLabels: app: slimfaas serviceName: slimfaas template: metadata: labels: app: slimfaas spec: # ... containers: - name: slimfaas image: docker.io/axaguildev/slimfaas:latest ports: - containerPort: 5000 # SlimFaas main port - containerPort: 3262 # SlimData port #env: # - name: SLIMDATA_CONFIGURATION # To start slimfaas with only 1 replica # value: | # {"coldStart":"true"} # ... --- apiVersion: v1 kind: Service metadata: name: slimfaas namespace: slimfaas-demo spec: selector: app: slimfaas ports: - name: "http" port: 5000 - name: "slimdata" port: 3262 ``` -------------------------------- ### Run the Demo Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasPlanetSaver/README.md Instructions to clone the SlimFaas repository, navigate to the SlimFaasPlanetSaver directory, install dependencies, and run the local development server to see the SlimFaasPlanetSaver in action. ```bash git clone https://github.com/SlimPlanet/slimfaas.git cd slimfaas/src/SlimFaasPlanetSaver npm i npm run dev ``` -------------------------------- ### React with Vite using SWC Source: https://github.com/slimplanet/slimfaas/blob/main/src/FibonacciReact/README.md This snippet shows the configuration for a React project in Vite, leveraging the SWC plugin for improved Fast Refresh performance. Installation of the SWC plugin is necessary. ```javascript import react from '@vitejs/plugin-react-swc' import { defineConfig } from 'vite' export default defineConfig({ plugins: [react()], }) ``` -------------------------------- ### SlimFaas Job Configuration Example Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/jobs.md An example of a SlimFaas job configuration, demonstrating the structure and available fields for defining a job, such as image, resource requests and limits, dependencies, and restart policy. ```json { "Configurations": { "fibonacci": { "Image": "axaguildev/fibonacci-batch:latest", "ImagesWhitelist": ["axaguides/fibonacci-batch:*"], "Resources": { "Requests": { "cpu": "400m", "memory": "400Mi" }, "Limits": { "cpu": "400m", "memory": "400Mi" } }, "DependsOn": ["fibonacci1"], "Environments": [], "BackoffLimit": 1, "Visibility": "Public", "NumberParallelJob": 2, "TtlSecondsAfterFinished": 36000, "RestartPolicy": "Never" } } } ``` -------------------------------- ### Install @axa-fr/slimfaas-planet-saver Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Installs the SlimFaas Planet Saver library using npm. This is the first step to integrate the library into your project. ```bash npm install @axa-fr/slimfaas-planet-saver ``` -------------------------------- ### Docker Quick Start Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/mcp.md Pulls and runs the latest multi-arch SlimFaas MCP Docker image. The API listens on port 8080 by default. ```bash docker run --rm -p 8080:8080 -e ASPNETCORE_URLS="http://*:8080" axaguildev/slimfaas-mcp:latest ``` -------------------------------- ### Install @axa-fr/slimfaas-planet-saver Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasPlanetSaver/README.md Installs the @axa-fr/slimfaas-planet-saver package using npm. ```javascript npm install @axa-fr/slimfaas-planet-saver ``` -------------------------------- ### SlimFaas Function Deployment Annotations Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This YAML demonstrates how to annotate a Kubernetes Deployment for a function (e.g., 'fibonacci1') to enable SlimFaas features. Annotations control auto-scaling, timeouts, parallel requests, dependencies, event subscriptions, and visibility. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: fibonacci1 namespace: slimfaas-demo spec: template: metadata: annotations: SlimFaas/Function: "true" # Enable SlimFaas SlimFaas/ReplicasMin: "0" SlimFaas/ReplicasAtStart: "1" SlimFaas/TimeoutSecondBeforeSetReplicasMin: "300" SlimFaas/NumberParallelRequest: "10" SlimFaas/DependsOn: "mysql,fibonacci2" SlimFaas/SubscribeEvents: "Public:my-event-name1,Private:my-event-name2,my-event-name3" SlimFaas/DefaultVisibility: "Public" # ... spec: containers: - name: fibonacci1 image: axaguildev/fibonacci:latest # ... ``` -------------------------------- ### Kubernetes RBAC Configuration for SlimFaas Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/get-started.md This YAML defines Service Accounts, Roles, and RoleBindings for SlimFaas to manage Kubernetes Deployments, StatefulSets, and view Endpoints. It grants necessary permissions for SlimFaas to interact with Kubernetes resources for auto-scaling and routing. ```yaml apiVersion: v1 kind: ServiceAccount metadata: name: slimfaas namespace: slimfaas-demo --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: deployment-statefulset-manager namespace: slimfaas-demo rules: # On ajoute ici le droit de lister/voir les pods dans ce namespace - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch"] - apiGroups: ["apps"] resources: ["deployments", "statefulsets"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: ["apps"] resources: ["deployments/scale", "statefulsets/scale"] verbs: ["get", "update", "patch"] - apiGroups: ["batch"] resources: ["jobs"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: slimfaas-deployment-statefulset-manager namespace: slimfaas-demo subjects: - kind: ServiceAccount name: slimfaas namespace: slimfaas-demo roleRef: kind: Role name: deployment-statefulset-manager apiGroup: rbac.authorization.k8s.io --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: endpoints-viewer namespace: slimfaas-demo rules: - apiGroups: [""] resources: ["endpoints"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: slimfaas-endpoints-viewer namespace: slimfaas-demo subjects: - kind: ServiceAccount name: slimfaas namespace: slimfaas-demo roleRef: kind: Role name: endpoints-viewer apiGroup: rbac.authorization.k8s.io ``` -------------------------------- ### Basic Usage of SlimFaasPlanetSaver Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Demonstrates how to initialize and use the SlimFaasPlanetSaver in a Vanilla JavaScript application. It includes configuration options for polling interval, fetch implementation, callbacks for updates and errors, and custom overlay messages. The example shows how to initialize the saver, start polling for environment status, and clean up resources when no longer needed. ```javascript import { SlimFaasPlanetSaver } from '@axa-fr/slimfaas-planet-saver'; const planetSaver = new SlimFaasPlanetSaver('http://slimfaas.mycompany.com', { interval: 2000, fetch: window.fetch, // or any fetch polyfill updateCallback: (data) => { console.log('Update callback data:', data); }, errorCallback: (error) => { console.error('Error detected:', error); }, overlayStartingMessage: '🌳 Starting the environment... 🌳', overlayNoActivityMessage: 'No activity yet — environment is sleeping.', overlayErrorMessage: 'An error occurred while starting the environment. Please try again later.', }); // Initialize and begin polling planetSaver.initialize(); planetSaver.startPolling(); // When you no longer need it: planetSaver.cleanup(); ``` -------------------------------- ### Run Development Server Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasSite/README.md Commands to start the Next.js development server using different package managers (npm, yarn, pnpm, bun). This allows for local development and testing. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### List Jobs in a Queue Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/jobs.md This snippet demonstrates how to list the status of jobs within a specific queue, named 'daisy' in this example, using an HTTP GET request. This is useful for monitoring job progress. ```bash curl -X GET http:///job/daisy ``` -------------------------------- ### MCP Prompt YAML Structure Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasMcp/wwwroot/index.html Example of the YAML structure for an MCP Prompt, defining active tools and their schemas. ```yaml # Example MCP Prompt YAML activeTools: - tool1 - tool2 tools: - name: tool1 description: Description for tool 1 inputSchema: type: object properties: param1: type: string outputSchema: type: object properties: result1: type: string - name: tool2 description: Description for tool 2 inputSchema: type: object properties: param2: type: integer outputSchema: type: object properties: result2: type: boolean ``` -------------------------------- ### SlimFaaS Lifecycle Management Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Outlines the essential lifecycle methods for initializing, starting, and cleaning up SlimFaaS, including the creation of overlay elements, injection of styles, binding of event listeners, and periodic environment checks. ```APIDOC instance.initialize() Description: Creates the overlay elements, injects styles, and binds event listeners (e.g., for mouse movement). instance.startPolling() Description: Begins periodic checks of the environment. If the environment is not ready, the overlay will appear. instance.cleanup() Description: Removes the overlay, styles, and any timers or event listeners when the component unmounts or monitoring is no longer needed. ``` -------------------------------- ### Clone SlimFaas Repository Source: https://github.com/slimplanet/slimfaas/blob/main/CONTRIBUTING.md This command clones the SlimFaas repository from GitHub to your local machine, allowing you to start contributing. ```sh git clone https://github.com/AxaFrance/SlimFaas.git ``` -------------------------------- ### SlimFaas Job Configuration Example Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/jobs.md This snippet demonstrates the structure of a SlimFaas job configuration within a Kubernetes ConfigMap. It defines a 'fibonacci' job with its image, resource requests and limits, dependencies, and other execution parameters. ```json { "Configurations": { "fibonacci": { "Image": "axaguildev/fibonacci-batch:latest", "ImagesWhitelist": [], "Resources": { "Requests": { "cpu": "400m", "memory": "400Mi" }, "Limits": { "cpu": "400m", "memory": "400Mi" } }, "DependsOn": ["fibonacci1"], "Environments": [], "BackoffLimit": 1, "Visibility": "Public", "NumberParallelJob": 2, "TtlSecondsAfterFinished": 36000, "RestartPolicy": "Never" } } } ``` -------------------------------- ### React Example Usage Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasPlanetSaver/README.md Demonstrates how to use the SlimFaasPlanetSaver component in a React application. It initializes the saver with a base URL, fetch function, and behavior configuration, and manages the display based on environment readiness. ```javascript import React, { useState, useEffect, useRef } from 'react'; import { SlimFaasPlanetSaver } from '@axa-fr/slimfaas-planet-saver'; const PlanetSaver = ({ children, baseUrl, fetch, noActivityTimeout=60000, behavior={} }) => { const [isFirstStart, setIsFirstStart] = useState(true); const environmentStarterRef = useRef(null); useEffect(() => { if (!baseUrl) return; if (environmentStarterRef.current) return; const instance = new SlimFaasPlanetSaver(baseUrl, { interval: 2000, fetch, behavior, updateCallback: (data) => { // Filter only the items that block the UI (WakeUp+BlockUI) const blockingItems = data.filter( (item) => instance.getBehavior(item.Name) === 'WakeUp+BlockUI' ); // If all blocking items are ready, set isFirstStart to false const allBlockingReady = blockingItems.every( (item) => item.NumberReady >= 1 ); if (allBlockingReady && isFirstStart) { setIsFirstStart(false); } }, errorCallback: (error) => { console.error('Error detected :', error); }, overlayStartingMessage: '🌳 Starting the environment.... 🌳', overlayNoActivityMessage: 'Waiting activity to start environment...', overlayErrorMessage: 'An error occurred when starting environment. Please contact an administrator.', overlaySecondaryMessage: 'Startup should be fast, but if no machines are available it can take several minutes.', overlayLoadingIcon: '🌍', overlayErrorSecondaryMessage: 'If the error persists, please contact an administrator.', noActivityTimeout }); environmentStarterRef.current = instance; // Initialiser les effets de bord instance.initialize(); instance.startPolling(); return () => { instance.cleanup(); environmentStarterRef.current = null; }; }, [baseUrl]); if (isFirstStart) { return null; } return <>{children}; }; export default PlanetSaver; ``` -------------------------------- ### SlimFaaS Lifecycle Management Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasPlanetSaver/README.md Provides methods to manage the lifecycle of a SlimFaaS instance. This includes initialization to set up the overlay and event listeners, starting periodic checks of the environment, and cleaning up resources when the instance is no longer needed. ```APIDOC instance.initialize() - Description: Creates the overlay elements, injects styles, and binds event listeners (e.g., for mouse movement). instance.startPolling() - Description: Begins periodic checks of the environment. If the environment is not ready, the overlay will appear. instance.cleanup() - Description: Removes the overlay, styles, and any timers or event listeners. This should be called when the component unmounts or monitoring is no longer required. ``` -------------------------------- ### PlanetSaver Component Usage Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Example of how to use the PlanetSaver React component, passing the baseUrl, fetch function, and a behavior map to configure environment service monitoring. ```jsx const behavior: { "api-speech-to-text": "WakeUp", "heavy-pdf-service": "WakeUp+BlockUI", "deprecated-service": "None" } ``` -------------------------------- ### SlimFaas Annotation Parameters Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/functions.md Details the parameters and their functions for SlimFaas annotations used in Kubernetes deployments. This includes enabling the function, setting minimum and starting replicas, defining inactivity timeouts, and limiting parallel requests per replica. ```APIDOC SlimFaas/Function: Description: Activates SlimFaas auto-scaling and routing for this pod. If not present or false, SlimFaas ignores the pod. Value: "true" SlimFaas/ReplicasMin: Description: The minimum number of replicas to maintain for the function. Setting to "0" allows scaling down to zero after inactivity. Value: "0" SlimFaas/ReplicasAtStart: Description: The number of replicas to initially wake up when traffic arrives or when manually triggered. Typically set to "1". Value: "1" SlimFaas/TimeoutSecondBeforeSetReplicasMin: Description: The number of inactivity seconds after which the function scales down to `ReplicasMin`. Defaults to 300 seconds. Value: "300" SlimFaas/NumberParallelRequest: Description: The maximum number of concurrent requests allowed for each replica. Additional requests are queued. Value: "10" ``` -------------------------------- ### SlimFaas Job API Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/jobs.md API endpoints for managing jobs within SlimFaas. **Trigger Job:** `POST /job/` Triggers a job with the specified name. The request body can include parameters to override default configurations such as Image, Args, DependsOn, Resources, Environments, BackoffLimit, TtlSecondsAfterFinished, and RestartPolicy. Example: ```bash curl -X POST http://localhost:30021/job/fibonacci { "Image": "axaguildev/fibonacci-batch:1.0.1", "Args": ["42", "43"], "DependsOn": ["fibonacci2"], "Resources": { "Requests": { "cpu": "200m", "memory": "200Mi" }, "Limits": { "cpu": "200m", "memory": "200Mi" } }, "Environments": [], "BackoffLimit": 1, "TtlSecondsAfterFinished": 100, "RestartPolicy": "Never" } ``` **List Jobs:** `GET /job/` Retrieves a list of jobs associated with a given queue or job family. Returns an array of job objects, each containing Id, Name, Status, PositionInQueue, InQueueTimestamp, and StartTimestamp. Example: ```bash curl -X GET http://localhost:30021/job/daisy [ { "Id": "1", "Name": "daisy-slimfaas-job-12772", "Status": "Queued", "PositionInQueue": 1, "InQueueTimestamp": 1, "StartTimestamp": -1 }, { "Id": "2", "Name": "daisy-slimfaas-job-12732", "Status": "Running", "PositionInQueue": -1, "InQueueTimestamp": 1, "StartTimestamp": 1 } ] ``` **Job Status Values:** `Queued`, `Pending`, `Running`, `Succeeded`, `Failed`, `ImagePullBackOff`. **Delete Job:** `DELETE /job//{id}` Deletes a specific job identified by its name and ID. This action cleans up the job's resources and logs. Returns `200 OK` on success or `404 Not Found` if the job does not exist. **Job Visibility:** Jobs can be configured as `Public` (accessible externally) or `Private` (accessible internally) using the `Visibility` field in the job configuration JSON. ```APIDOC POST /job/ Triggers a job with the specified name. The request body can include parameters to override default configurations such as Image, Args, DependsOn, Resources, Environments, BackoffLimit, TtlSecondsAfterFinished, and RestartPolicy. Example: ```bash curl -X POST http://localhost:30021/job/fibonacci { "Image": "axaguildev/fibonacci-batch:1.0.1", "Args": ["42", "43"], "DependsOn": ["fibonacci2"], "Resources": { "Requests": { "cpu": "200m", "memory": "200Mi" }, "Limits": { "cpu": "200m", "memory": "200Mi" } }, "Environments": [], "BackoffLimit": 1, "TtlSecondsAfterFinished": 100, "RestartPolicy": "Never" } ``` GET /job/ Retrieves a list of jobs associated with a given queue or job family. Returns an array of job objects, each containing Id, Name, Status, PositionInQueue, InQueueTimestamp, and StartTimestamp. Example: ```bash curl -X GET http://localhost:30021/job/daisy [ { "Id": "1", "Name": "daisy-slimfaas-job-12772", "Status": "Queued", "PositionInQueue": 1, "InQueueTimestamp": 1, "StartTimestamp": -1 }, { "Id": "2", "Name": "daisy-slimfaas-job-12732", "Status": "Running", "PositionInQueue": -1, "InQueueTimestamp": 1, "StartTimestamp": 1 } ] ``` **Job Status Values:** `Queued`, `Pending`, `Running`, `Succeeded`, `Failed`, `ImagePullBackOff`. DELETE /job//{id} Deletes a specific job identified by its name and ID. This action cleans up the job's resources and logs. Returns `200 OK` on success or `404 Not Found` if the job does not exist. **Job Visibility:** Jobs can be configured as `Public` (accessible externally) or `Private` (accessible internally) using the `Visibility` field in the job configuration JSON. ``` -------------------------------- ### SlimFaas Plug and Play Deployment Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/home.md SlimFaas is designed for easy deployment as a standard Kubernetes pod or StatefulSet. Integration with existing pods is achieved through simple annotation-based configuration. ```APIDOC Deployment: Standard Deployment: Deploy as a regular pod or StatefulSet. Minimal Configuration: Requires little setup. Integration: - Annotations: Add annotations to existing pods to include them in SlimFaas scaling logic. ``` -------------------------------- ### List Jobs Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/jobs.md Retrieves a list of jobs (queued, running, or finished) for a specific queue or job family using a GET request. ```bash GET http://localhost:30021/job/daisy ``` -------------------------------- ### Tool Rendering Structure Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasMcp/wwwroot/index.html HTML structure for rendering individual tools, including their name, description, input/output schemas, and execution controls. ```html

Tool Name

Tool Description

Input schema

...

Output schema

...
Content-Type: application/json
``` -------------------------------- ### Next.js Page Component Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasSite/README.md Example of a Next.js page component, likely located at app/page.tsx. This is the main entry point for the application's UI and auto-updates on file edits. ```typescript // app/page.tsx // This file is the main entry point for the Next.js application. // You can start editing the page by modifying this file. // The page auto-updates as you edit the file. ``` -------------------------------- ### Render Tool Information Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasMcp/wwwroot/index.html Renders a single tool's details into the DOM. It includes the tool's name, description, input and output schemas, and interactive elements like a run button and input form. It also visually highlights overridden schemas and disabled tools. ```javascript function renderTool(tool, bg, label) { // Badge for specific overrides let descColor = tool.isDescriptionOverridden ? "color:green; font-weight:bold;" : ""; let schemaBg = tool.isInputSchemaOverridden ? "background:#c2ffcf;" : ""; container.innerHTML += `

${tool.name} ${label ? `${label}` : ""}

${tool.description}

Input schema

${window.jsyaml.dump(tool.inputSchema)}

Output schema

${window.jsyaml.dump(tool.outputSchema)}
${tool.isDisabled ? 'Tool désactivé' : `
` }
Content-Type: ${tool.endpoint?.contentType || "application/json"}
`; if (!tool.isDisabled) { buildToolForm(tool); } } ``` -------------------------------- ### SlimFaaS Configuration Options Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Defines the configurable parameters for SlimFaaS, including timeouts for user activity and function wake-up, as well as options for customizing function behavior and providing a custom fetch implementation. ```APIDOC noActivityTimeout: number Description: How long (in ms) to wait for mouse movement before concluding there is no activity. If no activity is detected, a different overlay message is displayed. Default: 60000 wakeUpTimeout: number Description: If a function was recently “woken up,” we’ll skip re-calling wake-up for that function within this timeout window (in ms). Default: 60000 fetch: typeof fetch Description: Custom fetch function if you want to provide your own (e.g., for SSR, or if your environment doesn't have a global fetch). Default: Global fetch behavior: { [functionName: string]: 'WakeUp+BlockUI' | 'WakeUp' | 'None' } Description: Allows you to override how each function is handled: 1. "WakeUp+BlockUI": wakes the function and blocks the UI with the overlay until it’s ready. 2. "WakeUp": wakes without blocking the UI. 3. "None": no wake-up call. Default: Not set; defaults each function to "WakeUp+BlockUI" if unspecified. Notes on Behavior: - If a function is **not** specified in the behavior map, it defaults to "WakeUp+BlockUI". - "WakeUp+BlockUI" means the overlay will be shown until that function is NumberReady >= 1. - "WakeUp" means we attempt to wake up the function, but do not keep the overlay shown specifically for that function. - "None" means the function will neither be woken up nor block the UI. ``` -------------------------------- ### SlimFaasPlanetSaver Options Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/planet-saver.md Configuration options for the SlimFaasPlanetSaver constructor. These options allow customization of update and error handling, polling frequency, and overlay messages displayed during environment startup. ```APIDOC SlimFaasPlanetSaver Options: new SlimFaasPlanetSaver(baseUrl, options) Options: updateCallback: (data: any[]) => void - Function called after a successful fetch of the functions’ status. - The array data includes objects with info about each function, for example: `[{ Name: 'myFunc', NumberReady: 1 }, ...]`. - Default: `() => {}` errorCallback: (errorMessage: string) => void - Function called if an error occurs during the status fetch (e.g., network error). - Receives an errorMessage string. - Default: `() => {}` interval: number - How frequently (in ms) the polling should run. - Default: `5000` overlayStartingMessage: string - Main message shown on the overlay when the environment is waking up. - Default: `"🌳 Starting the environment.... 🌳"` overlayNoActivityMessage: string - Message shown if there is no user activity (mouse movement) for too long, but the environment is not ready yet. - Default: `"Waiting activity to start environment..."` overlayErrorMessage: string - Main message shown on the overlay if an error occurs (e.g., network error). - Default: `"An error occurred while starting the environment."` overlaySecondaryMessage: string - Secondary message shown on the overlay when the environment is waking up. - Default: `"Startup should be fast, but if no machines are available it can take several minutes."` overlayErrorSecondaryMessage: string - Secondary message shown on the overlay when an error occurs. - Default: `"If the error persists, please contact an administrator."` overlayLoadingIcon: string - Text or icon shown on the overlay. By default, it is animated to spin. - Default: `"🌍"` ``` -------------------------------- ### MCP Prompt Building and Management Source: https://github.com/slimplanet/slimfaas/blob/main/src/SlimFaasMcp/wwwroot/index.html Functions for building a minimal MCP prompt object by comparing loaded tools with UI-modified tools. It generates a diff of changes (added, modified, or disabled tools) and provides functionality to convert this object to YAML and Base64, and to apply changes from a YAML input. ```javascript function buildMinimalMcpPrompt({ loadedTools, uiTools }) { const prompt = {}; const origMap = new Map(loadedTools.map(t => [t.name, t])); const activeNow = uiTools.filter(t => !t.isDisabled).map(t => t.name); if (activeNow.length !== loadedTools.length) { prompt.activeTools = activeNow; } const modified = []; for (const t of uiTools) { const orig = origMap.get(t.name); if (!orig) { modified.push({ name: t.name, description: t.description, inputSchema: t.inputSchema }); continue; } const descChanged = t.description !== orig.description; const schemaChanged = JSON.stringify(t.inputSchema) !== JSON.stringify(orig.inputSchema); if (descChanged || schemaChanged) { const delta = { name: t.name }; if (descChanged) delta.description = t.description; if (schemaChanged) delta.inputSchema = t.inputSchema; modified.push(delta); } } if (modified.length) prompt.tools = modified; return prompt; } ``` ```javascript function toYamlBase64(obj) { const yaml = window.jsyaml.dump(obj); const b64 = btoa(unescape(encodeURIComponent(JSON.stringify(obj)))); return { yaml, b64 }; } ``` ```javascript function getMcpPromptBase64() { const promptObj = buildMinimalMcpPrompt({ loadedTools, uiTools: mergedTools.length ? mergedTools : loadedTools }); const { b64 } = toYamlBase64(promptObj); document.getElementById("mcpPromptBase64").textContent = b64; updateShareUrl(b64); return { json: promptObj, b64 }; } ``` ```javascript document.getElementById("mcpPrompt").addEventListener("input", getMcpPromptBase64); ``` ```javascript function applyMcpPrompt() { const yamlStr = document.getElementById("mcpPrompt").value; let prompt; try { prompt = window.jsyaml.load(yamlStr) || {}; } catch (e) { alert("Erreur YAML : " + e.message); return; } mcpPromptJson = prompt; const activeSet = prompt.activeTools ? new Set(prompt.activeTools) : null; mergedTools = []; const originMap = new Map(loadedTools.map(t => [t.name, t])); for (const orig of loadedTools) { const override = (prompt.tools || []).find(t => t.name === orig.name); const active = activeSet ? activeSet.has(orig.name) : true; mergedTools.push({ ...orig, description: override?.description || orig.description, inputSchema: override?.inputSchema || orig.inputSchema, isOverridden: !!override, isDescriptionOverridden: !!(override && override.description), isInputSchemaOverridden: !!(override && override.inputSchema), isDisabled: !active, isAdded: false, }); } if (prompt.tools) { for (const t of prompt.tools) { if (!originMap.has(t.name)) { mergedTools.push({ ...t, isOverridden: false, isDescriptionOverridden: !!t.description, isInputSchemaOverridden: !!t.inputSchema, isDisabled: false, isAdded: true, inputSchema: t.inputSchema || {}, description: t.description || "(Tool ajouté par YAML)", endpoint: { contentType: "application/json" }, }); } } } renderTools(true); getMcpPromptBase64(); } ``` ```javascript function renderTools(isMerge = false) { const container = document.getElementById("tools"); container.innerHTML = ""; const tools = isMerge ? mergedTools : loadedTools; for (const tool of tools) { let bg = "white", label = ""; if (tool.isAdded) { bg = "#d2ffd2"; label = "🆕 Tool ajouté"; } else if (tool.isDisabled) { bg = "#ffd6d6"; label = "⛔ Tool désactivé"; } else if (tool.isOverridden) { bg = "#f4fff0"; } // ... rest of the rendering logic } } ``` -------------------------------- ### Publish Event using cURL Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/events.md An example using cURL to publish an event to SlimFaas. It demonstrates the HTTP POST request, content type, JSON payload, and the target endpoint including the event name and path. ```bash curl -X POST -H "Content-Type: application/json" \ -d '{"data":"hello"}' \ http://localhost:30021/publish-event/my-event-name/hello ``` -------------------------------- ### SlimFaas Job Management Source: https://github.com/slimplanet/slimfaas/blob/main/documentation/home.md SlimFaas allows for the execution of one-off jobs triggered via HTTP. It provides configuration options for concurrency and visibility. ```APIDOC Job Execution: Trigger: Run jobs via HTTP calls. Configuration: - Concurrency: Control the number of concurrent job executions. - Visibility: Set jobs as public or private. ```