GithubHelp home page GithubHelp logo

jonparker / green-webhook Goto Github PK

View Code? Open in Web Editor NEW
7.0 2.0 1.0 1.48 MB

๐Ÿ’š ๐Ÿ’š GreenWebhook ๐Ÿ’š ๐Ÿ’š is a proxy or gateway between two systems that helps reduce your carbon footprint by dynamically routing or delaying traffic so that your workloads run when and where they will cause the lowest amount of carbon emissions.

Home Page: https://greenwebhook.netlify.app/

License: MIT License

Shell 0.95% JavaScript 1.59% TypeScript 92.99% CSS 4.18% HTML 0.30%
carbon-emissions carbon-footprint redwoodjs typescript webhooks

green-webhook's Introduction

๐Ÿ’š Welcome to Green Webhook! ๐Ÿ’š

Green Webhook is a proxy or gateway between two systems that intelligently chooses which endpoint to send a webhook event to in order to location shift or time shift (coming soon) compute workloads to the endpoint with the lowest carbon intensity. It uses the Carbon Aware SDK to check the impact of an increased demand on the electricity grid for the relevant locations.

By deploying your workload to multiple regions and configuring each endpoint along with its location within a Green Webhook you can reduce the carbon emissions caused by your workload.

Currently Green Webhook supports only Azure regions but as the Carbon Aware SDK adds more support for other locations Green Webhook will be able to support them too.

Green Webhook is built on RedwoodJS and uses:

React TypeScript GraphQL Prisma Postgres TailwindCSS

Create a webhook that runs code on your laptop via ngrok

  1. Create a NextJS app by running npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/master/basics/api-routes-starter"
  2. Create pages/api/user.js with:
export default function handler(req, res) {
  res.status(200).json({ name: "John Doe" });
}
  1. In a terminal run npm run dev
  2. Install Ngrok
  3. In a terminal run ngrok http 3000
  4. Copy the URL output by Ngrok and add /api/user to the end
  5. Log in to https://greenwebhook.netlify.app and create a new webhook
  6. Paste the URL from step 6 into the destination
  7. Click Save
  8. Click on the Invocation URI link to trigger the webhook
  9. Confirm that the response is 200 and contains JSON { name: "John Doe" }

Currently the Carbon Aware SDK only supports a limited list of locations but when more locations are supported then we will be able to allow you to put in the location where your computer or laptop is running in order to determine if it is the location with the lowest carbon intensity.

Getting started developing locally

Prerequisites

Start by installing dependencies:

yarn install

Whilst that is running, create a file in the root folder called .env and copy the following into it:

# Used to encrypt/decrypt session cookies. Change this value and re-deploy to log out all users of your app at once.
# Run yarn redwood generate secret and copy the value below
SESSION_SECRET=YOUR_SESSION_SECRET

# SendInBlue secret for reset password emails to work (optional)
# Requires setting up a free account at https://www.sendinblue.com/
SEND_IN_BLUE_KEY=YOUR_SENDINBLUE_SECRET
SEND_IN_BLUE_EMAIL=YOUr_SENDINBLUE_EMAIL_ADDRESS

DEPLOY_URL=http://localhost:8910

# Create a free database via https://railway.app and replace YOUR_RAILWAY_DB_URL bellow with the connection URL
DATABASE_URL="YOUR_RAILWAY_DB_URL"
CARBON_AWARE_API_BASE_URI="https://carbon-aware-api.azurewebsites.net"

# Run yarn redwood generate secret and copy the value below
SCHEDULED_WEBHOOKS_API_KEY=YOUR_SCHEDULED_WEBHOOK_SECRET_KEY

Replace YOUR_SESSION_SECRET with the secret generated by running yarn rw generate secret.

Replace YOUR_SCHEDULED_WEBHOOK_SECRET_KEY with the secret generated by running yarn rw generate secret a second time.

Create a free database via https://railway.app and copy the connection URL and replace YOUR_RAILWAY_DB_URL with it image

If you want to be able to send emails to reset passwords then you will need to create a SendInBlue account and create an API key and replace SEND_IN_BLUE_KEY with the API key.

Now when yarn install is finished you're ready to create the database tables in your Railway database.

yarn redwood prisma migrate dev

Once this finishes you should see tables appear in the database in Railway

image

Now you can run the app locally:

yarn rw dev

Your browser should automatically open to http://localhost:8910 where you'll see the Home page.

If you want to run scheduled webhooks you will need to periodically send a GET request to http://localhost:8910/.netlify/functions/schedule with the x-api-key header set to the YOUR_SCHEDULED_WEBHOOK_SECRET_KEY secret you created above.

Frontend first with Storybook

Don't know what your data models look like? That's more than ok โ€” Redwood integrates Storybook so that you can work on design without worrying about data. Mockup, build, and verify your React components, even in complete isolation from the backend:

yarn rw storybook

green-webhook's People

Contributors

jadetrue avatar jonparker avatar mr-loop-1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

mr-loop-1

green-webhook's Issues

Fix create new webhook button

Clicking on the create new green webhook button doesn't do anything.

Image

Image

Possibly there is something wrong in web/src/Routes.tsx but I haven't been able to work out what it is.

Remove the invocation uri from the frontend

Because we're using the id to generate the invocation URI we don't need to display the invocation URI field in the frontend.
Optionally the field could be removed from the database entirely but that's not as important as removing it from the frontend.

Update README with project brief

At the moment the README is just what was generated by RedwoodJS so we need to update it to include description of what the Green Webhook project is.

Implement external auth

Rather than use username and password auth stored in the DB an external provider should be used.
Alternatively a magic link in an email could be used for all sessions.

Password validation on signup

When a user creates an account or resets their password it should validate that the password is at least 8 characters has a strong complexity.

Host Carbon Aware SDK

The Carbon Aware SDK needs to be hosted somewhere that the Green Webhook can use it.
This will also require getting a Watttime API key.

Planning of user stories / features

Ideally this would be a group session but depending on our availability we might need to do this asynchronosly via chat.

  1. OPTIONAL Setting up the authentication (currently using database) with RedwoodJS
  2. DONE Setting up the deployment (choosing database hosting)
  3. Work out how we can schedule code to run with RedwoodJS (we're hosting on Netlify so most likely Netlify scheduled functions would be the best way https://docs.netlify.com/functions/scheduled-functions/ )
  4. DONE Setting up TailwindCSS
  5. Creating a Logo
  6. OPTIONAL Choosing a domain name (we already have a custom subdomain on Netlify)

Include an optional estimated processing time field

Include an estimated processing time field in the webhook form which would be optional.

What is needed are two things,

  1. a hidden hasEstimate boolean field that is passed along with the form data
  2. a estimated Time in seconds (optional) field that accepts an integer (1 upto 86399)

The hasEstimate field has false by default and true if any input is provided in the estimated Time field.

You may also include a note saying

if blank, estimation will be done based on actual processing times

Remove null locations from location list

Those locations whose Longitude and Latitude are listed as null in carbon aware sdk's azure regions are also listed in avaiable in "Create New Webhook".

Selecting these locations gives 500 Internal Server Error

Screenshot from 2022-10-29 14-54-03
Screenshot from 2022-10-29 14-59-26

Create project logo

Jade:

This was an idea I found for the logo. Any thoughts on this?

Image

Jon

It looks great. You should add it to the project if you want.

Create a scheduled invocations page for each webhook

In the /webhooks route, where all webhooks are listed, create a show "schedules" button.

On the new page, list all the schedules available for that webhook and seaprate them into two switchable menus of "scheduled" and "completed" based on the isCompleted boolean present in each element of array

So,

query FindWebhookById($id: String!) {
    webhook: webhook(id: $id) {
      id
      include: {
        scheduledInvocations: true
      }
    }
  }

could do the trick

Endpoints array size is fixed to 2

Even if a second endpoint is not filled on the create webhook page, the endpoints array is always of fixed length 2 like

endpoints  [
  'https://--first-endpoint-url--/api/user|asiapacific',
   '|na'
]

This leads to execution always going to the else block below.

const endpoints = webhook.destinationEndpoints.split(',')
let bestEndpoint = null
if (webhook.maxDelaySeconds > 0 && endpoints.length === 1) {
// Check Carbon Aware SDK for best time within maxDelaySeconds to call endpoint.
} else {
// Check Carbon Aware SDK for best location
const locations = endpoints.map((e) => e.split('|')[1])

There can be multiple approaches

  1. check for '|na' before or right here in the code and remove it from array
  2. modify frontend to show only 1 endpoint form and a "+" button for users to add more endpoints

Add caching of Carbon Aware data

If we have many requests that require getting the same data from the Carbon Aware API we should cache the data for 5 or 10 minutes.

The data couuld be cached in the database or just in memory (which may be more difficult as the code is running in a serverless function).

Success confirmation feature

Add a feature that allows for the endpoint to call back to the webhook on some URL to notify that the job or workload has completed. This would enable more analytics of how much carbon emissions were saved by the Green Webhook moving the workload.

Note that this wouldn't give an actual Kg of CO2 measurement as it would take much more work to know how many Killowatts of power the workload consumed.

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.