Giter Site home page Giter Site logo

nalgeon / codapi Goto Github PK

View Code? Open in Web Editor NEW
1.1K 13.0 47.0 85 KB

Interactive code examples for documentation, education and fun

Home Page: https://codapi.org

License: Apache License 2.0

Makefile 1.13% Go 98.77% Dockerfile 0.10%
playground sandbox snippets code-playground interactive-code interactive-snippets

codapi's Introduction

Interactive code examples

for documentation, education and fun ๐ŸŽ‰

Codapi is a platform for embedding interactive code snippets directly into your product documentation, online course or blog post.

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ def greet(name):              โ”‚
โ”‚   print(f"Hello, {name}!")    โ”‚
โ”‚                               โ”‚
โ”‚ greet("World")                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  Run โ–บ  Edit  โœ“ Done
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Hello, World!                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Codapi manages sandboxes (isolated execution environments) and provides an API to execute code in these sandboxes. It also provides a JavaScript widget codapi-js for easier integration.

Highlights:

  • Automatically converts static code examples into mini-playgrounds.
  • Lightweight and easy to integrate.
  • Sandboxes for any programming language, database, or software.
  • Open source. Uses the permissive Apache-2.0 license.

For an introduction to Codapi, see this post: Interactive code examples for fun and profit.

Installation

See Installing Codapi for details.

Usage (API)

Call /v1/exec to run the code in a sandbox:

POST https://api.codapi.org/v1/exec
content-type: application/json

{
    "sandbox": "python",
    "command": "run",
    "files": {
        "": "print('hello world')"
    }
}

sandbox is the name of the pre-configured sandbox, and command is the name of a command supported by that sandbox. See Adding a sandbox for details on how to add a new sandbox.

files is a map, where the key is a filename and the value is its contents. When executing a single file, it should either be named as the command expects, or be an empty string (as in the example above).

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": "python_run_9b7b1afd",
  "ok": true,
  "duration": 314,
  "stdout": "hello world\n",
  "stderr": ""
}
  • id is the unique execution identifier.
  • ok is true if the code executed without errors, or false otherwise.
  • duration is the execution time in milliseconds.
  • stdout is what the code printed to the standard output.
  • stderr is what the code printed to the standard error, or a compiler/os error (if any).

Usage (JavaScript)

See codapi-js to embed the JavaScript widget into a web page. The widget uses exactly the same API as described above.

Contributing

Contributions are welcome. For anything other than bugfixes, please first open an issue to discuss what you want to change.

Be sure to add or update tests as appropriate.

License

Copyright 2023 Anton Zhiyanov.

The software is available under the Apache-2.0 license.

Stay tuned

โ˜… Subscribe to stay on top of new features.

codapi's People

Contributors

deining avatar iamdeuterium avatar nalgeon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codapi's Issues

run in k8s

Heya!

Considering the actual deployment of codapi to run our sandboxes, we've come to the conclusion that all is shiny if codapi is run on a VM, with access to a docker daemon (same machine or not). That's fine, and it's likely the way to go, but I'm also wondering what it would take to make codapi play nice with running on K8s.

As far as I tried, it works from within a rigged dind (docker-in-docker) container, but that still requires the k8s pod to run in privileged mode. Now, it feels weird to require elevated privs just to drop them... So far, I haven't come up with much, though. Do you have any ideas or solved this conundrum before?

Thanks! ๐Ÿ™ƒ

Donation option?

I see that there's a commercial license option for $500/yr, but is there any lower tier for individual users who don't have a product that uses codapi yet, but they think it's neat and has potential?

Understanding the purpose of `files`

I'm really excited about this project and considering using it. I'm curious what the purpose of files is in the http api, and I couldn't find it documented anywhere. In every example I see it looks something like this

{
  ...
  files: { "": "someCode()" }
}

What else could go in files? If I wanted to include some data to be available in a sandbox, could it be in files?

HelloStar ่ฎกๅˆ’๏ผˆHelloStar Plan)

Hello, I am the initiator of HelloGitHub project.

"HelloStar Plan" is a Star growth plan for individual developers. I will use HelloGitHub's traffic (400,000 fans on the entire network) without reservation to help individual developers' open source projects and complete the cold drive phase of the project. Just for making friends and open source, I hope that after your project takes off, you can remember to have HelloGitHub as a friend on your open source road. Those who work hard on open source should be honored and become open source stars.

Requirements are as follows:

  1. Individual developer, loves open source
  2. Open source project Star < 1k, continuous maintenance for more than 3 months and plans to maintain it for a long time
  3. HelloGitHub fans

I plan to help 100 individual open source authors this year, including but not limited to providing help in promotion, operations, and contributions. As long as you treat me as a friend, everything will make sense. If you are interested, bring your open source project and come to me! WeChat: xueweihan (note: 100)

help in creating a tool sandbox

I'm trying to set up a tool sandbox where the tool would listen on a port, and you can basically configure this tool. Similar to this example on the website: https://codapi.org/try/caddy/

But I'm unable to figure out how to do it. I've looked at the code and tried setting it up, but it does not work. Are there any documents or pointers on creating something like that?

I then tried to set up something basic and then build from there, and I failed. I created a Docker image with HTTPBin and curl and tried doing this:

Dockerfile:

FROM kennethreitz/httpbin:latest

RUN adduser --home /sandbox --disabled-password --gecos '' sandbox

RUN apt-get update -y
RUN apt-get install -y curl

USER sandbox
WORKDIR /sandbox

boxes.json:

{
    "alpine": {
        "image": "codapi/alpine"
    },
    "python": {
        "image": "codapi/python"
    },
    "network-tools": {
        "image": "codapi/network-tools"
    },
    "httpbin": {
        "image": "codapi/httpbin"
    }
}

config.json:

{
    "pool_size": 8,
    "verbose": true,
    "box": {
        "runtime": "runc",
        "cpu": 1,
        "memory": 64,
        "network": "bridge",
        "writable": false,
        "volume": "%s:/sandbox:ro",
        "cap_drop": ["all"],
        "ulimit": ["nofile=96"],
        "nproc": 64
    },
    "step": {
        "user": "sandbox",
        "action": "run",
        "timeout": 5,
        "noutput": 4096
    }
}

httpbin.json:

{
    "run": {
        "engine": "docker",
        "entry": "main.sh",
        "steps": [
            {
                "box": "httpbin",
                "command": ["sh", "main.sh"],
                "noutput": 8192
            }
        ]
    }
}

I expected this to run the shell command (which will be a curl command) on the HTTPBin container, but the command fails with the error connect to 127.0.0.1 port 80 failed: Connection refused (isn't HTTPBin running?). I also tried other permutations of the configurations and tested the Docker image in the VM, but nothing seemed to work.

I'm obviously missing something, so I was wondering if there are examples I can look into.

Thanks.

Help me setup mysql sandbox

I have tried using step by step process written in add-sandbox.md file, but it's not working. Please guide me on how can I clean setup the MySQL sandbox on the system.

When using sh command API

curl -H "content-type: application/json" -d '{ "sandbox": "sh", "command": "run", "files": {"": "echo hello" }}' http://localhost:1313/v1/exec

the output is

{
    "id": "sh_run_dd27ed27",
    "ok": true,
    "duration": 650,
    "stdout": "hello\n",
    "stderr": ""
}

support matplotlib ?

import matplotlib.pyplot as plt
import numpy as np

# Create a figure and a set of subplots
fig, axs = plt.subplots(3, 3)

# Generate some random data
data = np.random.rand(3, 3)

# Plot the data on each subplot
for i in range(3):
    for j in range(3):
        axs[i, j].plot(data[i, :], data[j, :])

# Add a grid to each subplot
for ax in axs.flat:
    ax.grid(True)

# Show the plot
plt.show()

Gets the following errors :

Traceback (most recent call last):
  File "/sandbox/main.py", line 1, in <module>
    import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'
 (exit status 1)

Permission denied on alpine

I was trying to get the self-hosted server running Alpine 3.19 to work but ran into problems when accessing the temporary files from the docker image:

/srv/codapi # cat bin/test
#!/bin/sh

curl \
  -H "content-type: application/json" \
  -d '{ "sandbox": "sh", "command": "run", "files": {"": "echo hello" }}' \
  http://localhost:1313/v1/exec
/srv/codapi # bin/test | jq
{
  "id": "sh_run_b3a94e77",
  "ok": false,
  "duration": 416,
  "stdout": "",
  "stderr": "sh: can't open 'main.sh': Permission denied\n (exit status 2)"
}

The logs look similar:

/var/lib/codapi # tail -n2 /var/log/codapi/openrc.log 
2024/01/15 22:23:50 [run --rm --name sh_run_b3a94e77 --runtime runc --cpus 1 --memory 64m --network none --pids-limit 64 --user sandbox --read-only --volume /tmp/1851081613:/sandbox:ro --cap-drop all --ulimit nofile=96 codapi/alpine sh main.sh]
2024/01/15 22:23:50 โœ— sh_run_b3a94e77: sh: can't open 'main.sh': Permission denied (exit status 2)

The folder /tmp has the usual permissions.

I've documented my setup [here][1]. Is there something I've misconfigured?

Thanks for your help in advance!

[1]: https://git.tigger.cloud/public/codapi-setup-alpine

I have self-hosted the service, but I still get 403 - Forbidden

I hava self-hosted the service, but I still get 403 - Forbidden on my wordpress blog. Your domain is probably not allowed on Codapi. What should I do next?

```python
def greet(name):
  print(f"Hello, {name}!")

greet("World")
```

<codapi-snippet sandbox="python" editor="basic"></codapi-snippet>
<link rel="stylesheet" href="https://unpkg.com/@antonz/[email protected]/dist/snippet.css" />
<script src="https://unpkg.com/@antonz/[email protected]/dist/snippet.js"></script>
root@iZbp13y80xusaram14psd0Z:/opt/codapi# curl -H "content-type: application/json" -d '{ "sandbox": "sh", "command": "run", "files": {"": "echo hello" }}' http://localhost:1313/v1/exec
{"id":"sh_run_16572a32","ok":true,"duration":2091,"stdout":"hello","stderr":""}
root@iZbp13y80xusaram14psd0Z:/opt/codapi# ls
codapi                           codapi.log  images
codapi_0.8.0_linux_amd64.tar.gz  configs     LICENSE
root@iZbp13y80xusaram14psd0Z:/opt/codapi#

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.