• Stars
    star
    137
  • Rank 266,121 (Top 6 %)
  • Language
    TypeScript
  • License
    Other
  • Created about 2 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Estimate the carbon footprint of a user scenario on a web application

GreenFrame CLI

Estimate the carbon footprint of a user scenario on a web application. Full-stack analysis (browser, screen, network, server).

Can be used standalone, in a CI/CD pipeline, and in conjunction with the greenframe.io service.

In A Nutshell

The share of digital technologies in global greenhouse gas emissions has passed air transport, and will soon pass car transport (source). At 4% of total emissions, and with a growth rate of 9% per year, the digital sector is a major contributor to global warming.

How do developers adapt their practices to build less energy intensive web applications?

GreenFrame is a command-line tool that estimates the carbon footprint of web apps at every stage of the development process. Put it in your Continuous Integration workflow to get warned about "carbon leaks", and force a threshold of maximum emissions.

For instance, to estimate the energy consumption and carbon emissions of a visit to a public web page, call greenframe analyze:

$ greenframe analyze https://marmelab.com
✅ main scenario completed
The estimated footprint is 0.038 g eq. co2 ± 1.3% (0.085 Wh).

Installation

To install GreenFrame CLI, type the following command in your favorite terminal:

curl https://assets.greenframe.io/install.sh | bash

To verify that GreenFrame CLI has correctly been installed, type:

$ greenframe -v
enterprise-cli/1.5.0 linux-x64 node-v16.14.0

Usage

By default, GreenFrame runs a "visit" scenario on a public web page and computes the energy consumption of the browser, the screen, and the public network. But it can go further.

Custom Scenario

You can run a custom scenario instead of the "visit" scenario by passing a scenario file to the analyze command:

$ greenframe analyze https://marmelab.com ./my-scenario.js

GreenFrame uses PlayWright to run scenarios. A custom PlayWright scenario looks like the following:

// in my-scenario.js
const scenario = async (page) => {
    await page.goto('', { waitUntil: 'networkidle' }); // Go to the baseUrl
    await page.waitForTimeout(3000); // Wait for 3 seconds
    await page.scrollToElement('footer'); // Scroll to the footer (if present)
    await page.waitForNetworkIdle(); // Wait every request has been answered as a normal user.
};

module.exports = scenario;

Check the PlayWright documentation on writing tests for more information.

You can test your scenario using the greenframe open command. It uses the local Chrome browser to run the scenario:

$ greenframe open https://marmelab.com ./my-scenario.js

You can write scenarios by hand, or use the PlayWright Test Generator to generate a scenario based on a user session.

Full-Stack Analysis

You can monitor the energy consumption of other docker containers while running the scenario. This allows spawning an entire infrastructure and monitoring the energy consumption of the whole stack.

For instance, if you start a set of docker containers using docker-compose, containing the following services:

$ docker ps
CONTAINER ID   IMAGE        COMMAND                  CREATED         STATUS        PORTS                   NAMES
d94f1c458c19   node:16      "docker-entrypoint.s…"   7 seconds ago   Up 7 seconds  0.0.0.0:3003->3000/tcp  enterprise_app
f024c10e666b   node:16      "docker-entrypoint.s…"   7 seconds ago   Up 7 seconds  0.0.0.0:3006->3006/tcp  enterprise_api
b6b5f8eb9a6d   postgres:13  "docker-entrypoint.s…"   8 seconds ago   Up 8 seconds  0.0.0.0:5434->5432/tcp  enterprise_db

You can run an analysis on the full stack (the browser + the 3 server containers) by passing the --containers and --databaseContainers option:

$ greenframe analyze https://localhost:3000/ ./my-scenario.js --containers="enterprise_app,enterprise_api" --databaseContainers="enterprise_db"

GreenFrame needs to identify database containers because it computes the impact of network I/O differently between the client and the server, and within the server infrastructure.

Using An Ad Blocker

Third-party tags can be a significant source of energy consumption. When you use the --useAdblock option, GreenFrame uses an Ad Blocker to let you estimate that cost.

Run two analyses, a normal one then an ad-blocked one, and compare the results:

$ greenframe analyze https://adweek.com
The estimated footprint is 0.049 g eq. co2 ± 1% (0.112 Wh).
$ greenframe analyze https://adweek.com --useAdblock
The estimated footprint is 0.028 g eq. co2 ± 1.1% (0.063 Wh).

In this example, the cost of ads and analytics is 0.049g - 0.028g = 0.021g eq. co2 (42% of the total footprint).

Defining A Threshold

The greenframe CLI was designed to be used in a CI/CD pipeline. You can define a threshold in g eq. co2 to fail the build if the carbon footprint is too high:

$ greenframe analyze https://cnn.com --threshold=0.045
❌ main scenario failed
The estimated footprint at 0.05 g eq. co2 ± 1.3% (0.114 Wh) passes the limit configured at 0.045 g eq. co2.

In case of failed analysis, the CLI exits with exit code 1.

Syncing With GreenFrame.io

If you want to get more insights about your carbon footprint, you can sync your analysis with GreenFrame.io. This service provides:

  • A dashboard to monitor your carbon footprint over time
  • A detailed analysis of your carbon footprint, with a breakdown by scenario, container, scenario step, and component
  • A comparison with previous analyses on the main branch (for Pull Request analysis)

image

To get started, subscribe to GreenFrame.io and create a new project. Then, get your token from the greenframe project page. Pass this token to each greenframe command using the GREENFRAME_SECRET_TOKEN environment variable:

$ GREENFRAME_SECRET_TOKEN=your-token-here greenframe analyze https://marmelab.com
✅ main scenario completed
The estimated footprint is 0.038 g eq. co2 ± 9.6% (0.086 Wh).
Check the details of your analysis at https://app.greenframe.io/analyses/7d7b7777-600c-4399-842f-b70db9408f53

When using a greenframe.io token, the greenframe analyze command generates an online report with much more details than the estimated footprint, and outputs its URL on the console.

Alternately, you can export this environment variable in your shell configuration file (.bashrc, .zshrc, etc.).

export GREENFRAME_SECRET_TOKEN=your-token-here

Benchmarking Against Other Sites

How does the carbon footprint of your site compare to other sites?

GreenFrame.io runs a "visit" scenario over many websites in several categories. This allows you to compare your site to other sites in the same category.

If you're using a custom scenario, run the same scenario over another URL to compare the results.

The problem is that a given "scenario" may need adaptations to run on another site. For instance, the "add to cart" scenario may need to click on a different button to add an item to the cart. So the hard part of benchmarking is to define a scenario for each site.

Diffing Against Previous Analyses

If you're using GreenFrame.io, you can compare your analysis with the previous one on the main branch. This allows you to monitor the evolution of your carbon footprint over time.

The greenframe CLI will automatically detect that you're in a git checkout, and store the commit hash in the analysis metadata. When run on a branch, it will also look for the latest analysis on the main branch, and compare the two. The results are visible on the analysis page on GreenFrame.io.

Tip: You can customize the name of the main branch using the .greenframe.yml config file.

Using a Config File

Instead of passing all options on the command line, you can use a .greenframe.yml file to configure the CLI. This file must be located in the same directory as the one where you run the greenframe CLI.

baseURL: YOUR_APP_BASE_URL
scenarios:
    - path: PATH_TO_YOUR_SCENARIO_FILE
      name: My first scenario
      threshold: 0.1
projectName: YOUR_PROJECT_NAME
samples: 3
distant: false
useAdblock: true
ignoreHTTPSErrors: true
locale: 'fr-FR',
timezoneId: 'Europe/Paris',
containers:
    - 'CONTAINER_NAME'
    - 'ANOTHER_CONTAINER_NAME'
databaseContainers:
    - 'DATABASE_CONTAINER_NAME'

More Information / Troubleshooting

Check the docs at greenframe.io:

https://docs.greenframe.io/

How Does GreenFrame Work?

GreenFrame relies on a scientific model of the energy consumption of a digital system built in collaboration with computer scientists at Loria.

While running the scenario, GreenFrame uses docker stats to collect system metrics (CPU, memory, network and disk I/O, scenario duration) every second from the browser and containers.

It then uses the GreenFrame Model to convert each of these metrics into energy consumption in Watt.hours. GreenFrame sums up the energy of all containers over time, taking into account a theoretical datacenter PUE (set to 1.4, and configurable) for server containers. This energy consumption is then converted into CO2 emissions using a configurable "carbon cost of energy" parameter (set to 442g/kWh by default).

GreenFrame repeats the scenario 3 times and computes the average energy consumption and CO2 emissions. It also computes the standard deviation of energy consumption and CO2 emissions to provide a confidence interval.

For more details about the GreenFrame Model, check this article on the Marmelab blog:

GreenFrame.io: What is the carbon footprint of a web page?.

Which Factors Influence The Carbon Footprint?

Based on our research, the carbon footprint of a web page depends on:

  • The duration of the scenario
  • The size of the page (HTML, CSS, JS, images, fonts, etc.)
  • The amount of JS executed on the browser
  • The number of third-party tags (ads, analytics, etc.)
  • The complexity of the page (number of DOM elements, number of layout changes, etc.)

Server containers have a low impact on the carbon footprint (around 5% in most cases).

This means that the lowest hanging fruit for optimizing the emissions of a web page is to use Web Performance Optimization (WPO) techniques.

Commands

greenframe analyze [BASEURL] [SCENARIO]

Create an analysis on GreenFrame server.

USAGE
  $ greenframe analyze [BASEURL] [SCENARIO] [-C <value>] [-K <value>] [-t <value>] [-p <value>] [-c <value>]
    [--commitId <value>] [-b <value>] [-s <value>] [-d] [-a] [-i] [--locale] [--timezoneId] [-e <value>] [-E <value>]
    [--dockerdHost <value>] [--dockerdPort <value>] [--containers <value>] [--databaseContainers <value>]
    [--kubeContainers <value>] [--kubeDatabaseContainers <value>]

ARGUMENTS
  BASEURL   Your baseURL website
  SCENARIO  Path to your GreenFrame scenario

FLAGS
  -C, --configFile=<value>          Path to config file
  -E, --envFile=<value>             File of environment vars
  -K, --kubeConfig=<value>          Path to kubernetes client config file
  -a, --useAdblock                  Use an adblocker during analysis
  -b, --branchName=<value>          Pass branch name manually
  -c, --commitMessage=<value>       Pass commit message manually
  -d, --distant                     Run a distant analysis on GreenFrame Server instead of locally
  -e, --envVar=<value>...           List of environment vars to read in the scenarios
  -i, --ignoreHTTPSErrors           Ignore HTTPS errors during analysis
  -p, --projectName=<value>         Project name
  -s, --samples=<value>             Number of runs done for the score computation
  -t, --threshold=<value>           Consumption threshold
  --commitId=<value>                Pass commit id manually
  --containers=<value>              Pass containers manually
  --databaseContainers=<value>      Pass database containers manually
  --dockerdHost=<value>             Docker daemon host
  --dockerdPort=<value>             Docker daemon port
  --kubeContainers=<value>          Pass kubebernetes containers manually
  --kubeDatabaseContainers=<value>  Pass kubebernetes database containers manually
  --locale                          Set greenframe browser locale
  --timezoneId                      Set greenframe browser timezoneId

DESCRIPTION
  Create an analysis on GreenFrame server.

See code: dist/commands/analyze.ts

greenframe kube-config

Configure kubernetes cluster to collect greenframe metrics

USAGE
  $ greenframe kube-config [-C <value>] [-K <value>] [-D]

FLAGS
  -C, --configFile=<value>  Path to config file
  -D, --delete              Delete daemonset and namespace from kubernetes cluster
  -K, --kubeConfig=<value>  Path to kubernetes client config file

DESCRIPTION
  Configure kubernetes cluster to collect greenframe metrics
  ...
  greenframe kube-config

See code: dist/commands/kube-config.ts

greenframe open [BASEURL] [SCENARIO]

Open browser to develop your GreenFrame scenario

USAGE
  $ greenframe open [BASEURL] [SCENARIO] [-C <value>] [-a] [--ignoreHTTPSErrors] [--locale] [--timezoneId]

ARGUMENTS
  BASEURL   Your baseURL website
  SCENARIO  Path to your GreenFrame scenario

FLAGS
  -C, --configFile=<value>  Path to config file
  -a, --useAdblock          Use an adblocker during analysis
  --ignoreHTTPSErrors       Ignore HTTPS errors during analysis
  --locale                  Set greenframe browser locale
  --timezoneId              Set greenframe browser timezoneId

DESCRIPTION
  Open browser to develop your GreenFrame scenario
  ...
  greenframe analyze ./yourScenario.js https://greenframe.io

See code: dist/commands/open.ts

greenframe update [CHANNEL]

Update GreenFrame to the latest version

USAGE
  $ greenframe update [CHANNEL]

ARGUMENTS
  CHANNEL  [default: stable] Release channel

DESCRIPTION
  Update GreenFrame to the latest version
  ...
  greenframe update

See code: dist/commands/update.ts

Development

The GreenFrame CLI is written in Node.js. Install depencencies with:

yarn

To run the CLI locally, you must compile the TypeScript files with:

$ yarn build

Then you can run the CLI:

$ ./bin/run analyze https://greenframe.io ./src/examples/visit.js

While developing, instead of running yarn build each time you make a change, you can watch for changes and automatically recompile with:

$ yarn watch

License

GreenFrame is licensed under the Elastic License v2.0.

This means you can use GreenFrame for free both in open-source projects and commercial projects. You can run GreenFrame in your CI, whether your project is open-source or commercial.

But you cannot build a competitor to greenframe.io, i.e. a paid service that runs the GreenFrame CLI on demand.

More Repositories

1

react-admin

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design
TypeScript
22,823
star
2

gremlins.js

Monkey testing library for web apps and Node.js
JavaScript
8,971
star
3

ng-admin

Add an AngularJS admin GUI to any RESTful API
JavaScript
3,968
star
4

awesome-rest

A collaborative list of great resources about RESTful API architecture, development, test, and performance
3,457
star
5

json-graphql-server

Get a full fake GraphQL API with zero coding in less than 30 seconds.
JavaScript
1,930
star
6

universal.css

The only CSS you will ever need
CSS
1,260
star
7

EventDrops

A time based / event series interactive visualization using d3.js
JavaScript
1,236
star
8

restful.js

A pure JS client for interacting with server-side RESTful resources. Think Restangular without Angular.
JavaScript
969
star
9

gaudi

Gaudi allows to share multi-component applications, based on Docker, Go, and YAML.
Go
566
star
10

ng-admin-react

Add a ReactJS admin GUI to any RESTful API. Deprecated: see admin-on-rest for a full rewrite
JavaScript
544
star
11

FakeRest

Patch fetch/XMLHttpRequest to fake a REST API server in the browser, based on JSON data.
JavaScript
407
star
12

admin-on-rest

A frontend framework for building admin SPAs on top of REST services, using React and Material Design.
JavaScript
400
star
13

admin-on-rest-demo

Source of the admin-on-rest react.js demo, using a dummy REST service powered by FakeRest
JavaScript
329
star
14

ng-admin-demo

Source of the ng-admin angular.js demo, using a dummy REST service powered by FakeRest
JavaScript
305
star
15

sedy

A GitHub bot bringing the sed command to code reviews
JavaScript
266
star
16

javascript-boilerplate

Node.js+Koa.js+PostgreSQL+React.js+Webpack+Mocha+Makefile, a starter kit for new apps
JavaScript
253
star
17

ArchitectureTree

Draw and share your software architecture without diagramming software. Uses d3.js and Angular.js.
JavaScript
218
star
18

comfygure

Encrypted and versioned configuration store built with collaboration in mind
JavaScript
192
star
19

microrest.php

A micro web application providing a REST API on top of any relational database, using Silex and Doctrine DBAL
PHP
186
star
20

graphql-schema-from-json

Guess a GraphQL schema from json data
JavaScript
183
star
21

tree.js

Tree.js is a JavaScript library to build and manipulate hookable trees.
JavaScript
148
star
22

ra-supabase

Supabase adapter for react-admin, the frontend framework for building admin applications on top of REST/GraphQL services.
TypeScript
144
star
23

atomic-crm

A full-featured CRM built with React, react-admin, and Supabase.
TypeScript
113
star
24

ng-admin-postgrest

Demo of an integration between ng-admin and PostgREST
JavaScript
111
star
25

phpcr-browser

Web interface for browsing PHPCR repositories, using Silex and AngularJS
CSS
103
star
26

sketch-by-phone

A proof-of-concept of Augmented Reality with HTML5
JavaScript
96
star
27

ArcheoloGit

Where should you focus the maintenance efforts? ArcheoloGit is a visualization of age and dev activity for software, powered by d3.js.
JavaScript
95
star
28

phpunit-d3-report

Visualize the slowest parts of a PHPUnit testsuite using d3.js
JavaScript
93
star
29

GraphQL-example

An example code structure for a GraphQL-powered mobile app. Contains client and server code.
JavaScript
86
star
30

make-docker-command

Seamlessly execute commands (composer, bower, compass) in isolation using docker and make.
Makefile
83
star
31

aor-graphql

Packages related to using GraphQL with Admin-on-rest
JavaScript
81
star
32

react-admin-demo

Source of the react-admin react.js demo, using a dummy REST service powered by FakeRest
67
star
33

ra-auth-acl

Access Control List authProvider and helpers for React Admin
TypeScript
64
star
34

aor-dependent-input

A component for displaying input depending on other inputs values in Admin-on-rest
JavaScript
60
star
35

argos

docker monitoring experiment
58
star
36

react-md-motion

Material design motions with react
JavaScript
54
star
37

Raphael.InlineTextEditing

Raphael Plugin allowing inline edition of SVG text elements
JavaScript
54
star
38

ra-example-oauth

An example of OpenID Connect implementation on React Admin
TypeScript
53
star
39

aor-simple-graphql-client

A simple GraphQL client for admin-on-rest
JavaScript
48
star
40

ZeroDollarHomePage

A decentralized ad server running on the blockchain
JavaScript
45
star
41

SonataElasticaBundle

Power the Sonata Admin list view and filters by an ElasticSearch index to speed up navigation.
PHP
43
star
42

aor-permissions

A component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
JavaScript
42
star
43

react-admin-crm

A CRM build with react-admin, used as a demo for the capabilities of the framework
HTML
40
star
44

ra-in-memory-jwt

Manage React-admin authentication with jwt in memory, not in local storage
JavaScript
39
star
45

koa-multifetch

A Koa.js middleware for performing internal batch requests
JavaScript
36
star
46

gollabedit

Experimental collaborative editor written in Go
Go
33
star
47

admin-config

Configuration API to describe an administration interface. Used by ng-admin and react-admin.
JavaScript
31
star
48

ocaml-invader

Ocaml Space-Invader implementation using OpenGL
OCaml
29
star
49

admin-on-rest-graphql-demo

JavaScript
29
star
50

ra-data-google-sheets

A data provider for react-admin, based on Google Sheets
JavaScript
26
star
51

ra-datagrid

Integration of Material-ui's <Datagrid> into react-admin
TypeScript
26
star
52

battery-friendly-timer

Mobile applications using setInterval to poll a server are a battery hogs. Save battery life by fetching data at the right moment.
JavaScript
25
star
53

MobileInsight

A Mobile web app to browse PHP code analyses made by SensioLabsInsight, built with Angular.js and Ionic.
JavaScript
25
star
54

yolo

Typo-tolerant runtime object proxy for fast JavaScritp typers
JavaScript
24
star
55

aor-rich-text-input

<RichTextInput> component for admin-on-rest, useful for editing HTML code in admin GUIs
CSS
23
star
56

timeline-react-admin

Support for a tutorial about custom List views with react-admin
JavaScript
23
star
57

strapi-beerdex

StrapiJS Example Application For Beer Management
JavaScript
23
star
58

chrome-bug-report-wizard

Chrome plugin automating Bug Tracker issue creation with screenshot and browser details
JavaScript
23
star
59

highlight-search-term

Highlight search term in a page. Vanilla JS, compatible with frontend frameworks (React, Vite, Angular, etc).
JavaScript
22
star
60

ra-enterprise-demo

TypeScript
20
star
61

solid-admin

TypeScript
20
star
62

argos-cli

19
star
63

aor-realtime

JavaScript
17
star
64

svelte-sse-chat

Chat Example Application Using SvelteJS and Chat
Svelte
15
star
65

uptime

A prototype of website monitoring tool, written in Go and React.js, modeled after fzaninotto/uptime
JavaScript
15
star
66

reactive-beers

Reactive Beers is an example application using CouchDB and PouchDB
JavaScript
15
star
67

reversi-reason

🐪 ReasonML implementation of Reversi Game
OCaml
13
star
68

MobileAudience

Mobile Webapp mixing D3.js with a touch UI ; shows TV audiences and market shares for 8 fictive TV channels across several days.
JavaScript
13
star
69

curator-ai

An AI-powered news curator. It reads a list of articles, selects the best ones depending on a list of interests, and summarizes them into an easy-to-read news feed. Powered by the OpenAI API.
TypeScript
13
star
70

ng-tree

An Angular.js module for using tree.js
JavaScript
12
star
71

docker-parallel-phpunit-demo

How to use Docker to run PHPUnit tests in parallel
PHP
12
star
72

skelt

{ } Skelt is a simple templating engine for object literals.
JavaScript
12
star
73

redux-form-inspector

An HOC for computing dynamic props from values inside an existing redux-form component.
JavaScript
12
star
74

virothello

💫 Othello Game Using Augmented Reality And Viro
JavaScript
12
star
75

coPostgresQuery

Query builder for PostgreSQL in Node.js, built for async
JavaScript
11
star
76

phpcr-api

PHP
11
star
77

ra-keycloak

TypeScript
11
star
78

svg_to_png

Convert an SVG file to a PNG image. Uses headless Chrome for rendering.
JavaScript
11
star
79

aor-json-rest-client

A local REST client for admin-on-rest
JavaScript
10
star
80

docker-compass

Dockerfile
10
star
81

dobble

Generate a valid deck of cards for Dobble in ECMAScript6
JavaScript
10
star
82

ra-sqlite-dataprovider

POC of a dataprovider using a sqlite database hosted on a static server
JavaScript
9
star
83

checkoid

Experimental validator library allowing to combine validator like you would lego piece.
TypeScript
9
star
84

gql-profiler

A standalone performance profiler for GraphQL resolvers
JavaScript
9
star
85

liMonade

A Monad library to make Monad simple.
TypeScript
9
star
86

dedale

A wood labyrinth game in the browser
JavaScript
9
star
87

silex-multifetch

A Silex provider for performing internal batch requests
PHP
9
star
88

treedu

Graphical Disk Usage command for the terminal, using Node.js, d3.js, blessed, and Drawille
JavaScript
9
star
89

ra-shadcn-demo

An example showing how to use react-admin in headless mode with shadcn
TypeScript
9
star
90

ra-auth-cognito

An auth provider for react-admin which handles authentication with AWS Cognito.
TypeScript
9
star
91

ra-richtext-tiptap

TypeScript
8
star
92

ra-strapi-demo

JavaScript
8
star
93

ra-example-kanban

Example of a Kanban board built with React Admin
TypeScript
8
star
94

docker-composer-hhvm

8
star
95

Asteroids.js

A one day experiment to bringing the Asteroids game to the browser, using a mobile device as controller, Node.js, Raphaël, and socket.io.
JavaScript
8
star
96

docker-bower

Dockerfile
8
star
97

ra-tailwind-demo

An example showing how to use react-admin in headless mode with tailwind
TypeScript
8
star
98

web-myna

Record then emulate your api.s for testing and development
JavaScript
7
star
99

puppeteer-accessibility

JavaScript
7
star
100

ninja-coder

Code with your entire body like a Ninja
JavaScript
7
star