├── .formatter.exs ├── .gitignore ├── .vscode └── settings.json ├── README.md ├── assets ├── .babelrc ├── css │ ├── app.scss │ └── phoenix.css ├── js │ ├── app.js │ ├── chart.js │ └── heatmap.js ├── package-lock.json ├── package.json ├── static │ ├── favicon.ico │ ├── images │ │ └── phoenix.png │ └── robots.txt └── webpack.config.js ├── config ├── config.exs ├── dev.exs ├── prod.exs ├── prod.secret.exs └── test.exs ├── img ├── linearscale.png ├── logo.png ├── logscale.png └── logscale2.png ├── lib ├── spotlight.ex ├── spotlight │ ├── application.ex │ └── request_time_collector.ex ├── spotlight_web.ex └── spotlight_web │ ├── channels │ └── user_socket.ex │ ├── endpoint.ex │ ├── gettext.ex │ ├── live │ ├── page_live.ex │ └── page_live.html.leex │ ├── router.ex │ ├── telemetry.ex │ ├── templates │ └── layout │ │ ├── app.html.eex │ │ ├── live.html.leex │ │ └── root.html.leex │ └── views │ ├── error_helpers.ex │ ├── error_view.ex │ └── layout_view.ex ├── mix.exs ├── mix.lock ├── priv └── gettext │ ├── en │ └── LC_MESSAGES │ │ └── errors.po │ └── errors.pot └── test ├── spotlight_web ├── live │ └── page_live_test.exs └── views │ ├── error_view_test.exs │ └── layout_view_test.exs ├── support ├── channel_case.ex └── conn_case.ex └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | [ 2 | import_deps: [:phoenix], 3 | inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where 3rd-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | spotlight-*.tar 24 | 25 | # If NPM crashes, it generates a log, let's ignore it too. 26 | npm-debug.log 27 | 28 | # The directory NPM downloads your dependencies sources to. 29 | /assets/node_modules/ 30 | 31 | # Since we are building assets from assets/, 32 | # we ignore priv/static. You may want to comment 33 | # this depending on your deployment strategy. 34 | /priv/static/ 35 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/.vscode/settings.json -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Spotlight Logo](img/logo.png) 2 | 3 | # Phoenix Response Time Graphs 4 | 5 | :heavy_check_mark: Very very low overhead (powered by [DogSketch](https://github.com/moosecodebv/dog_sketch)) 6 | 7 | :heavy_check_mark: Cluster-wide performance charts (not just a single node!) 8 | 9 | :heavy_check_mark: No external dependencies (runs 100% in-BEAM) 10 | 11 | :heavy_check_mark: Accurate p50, p90, p99 and throughput 12 | 13 | :heavy_check_mark: Linear and Log scale 14 | 15 | ## Linear Scale 16 | ![Spotlight linear scale](img/linearscale.png) 17 | 18 | ## Log Scale 19 | ![Spotlight log scale](img/logscale2.png) 20 | 21 | # Caveat 22 | 23 | To our knowledge nobody is running this in production yet. BUT, in theory, it should be able to track an obscene number of requests without slowing down your system. I suspect it will handle at least 100k requests per second per node with ease. Give it a try and let us know! 24 | 25 | # Installation 26 | 27 | 1. Add `spotlight` to your list of dependencies 28 | 2. Configure LiveView (if you haven't already) 29 | 3. Add spotlight to your Phoenix router 30 | 31 | ## 1. Add `spotlight` to your list of dependencies 32 | 33 | Add to `mix.exs`: 34 | 35 | ```elixir 36 | def deps do 37 | [ 38 | {:spotlight, "~> 0.1.0"} 39 | ] 40 | end 41 | ``` 42 | 43 | Then run `mix deps.get`. 44 | 45 | ## 2. [Configure LiveView (if you haven't already)](https://hexdocs.pm/phoenix_live_view/installation.html) 46 | 47 | ## 3. Add `spotlight` to your Phoenix router 48 | 49 | ```elixir 50 | # lib/my_app_web/router.ex 51 | use MyAppWeb, :router 52 | import SpotlightWeb.Router 53 | 54 | ... 55 | 56 | scope "/" do 57 | pipe_through :browser 58 | spotlight("/spotlight") 59 | end 60 | ``` 61 | 62 | We heavily recommend that you put Spotlight behind some kind of authentication before adding it to your production servers. 63 | -------------------------------------------------------------------------------- /assets/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /assets/css/app.scss: -------------------------------------------------------------------------------- 1 | /* This file is for your main application css. */ 2 | @import "./phoenix.css"; 3 | @import "../node_modules/nprogress/nprogress.css"; 4 | @import "../node_modules/uplot/dist/uPlot.min.css"; 5 | @import url('https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400&display=swap'); 6 | 7 | /* LiveView specific classes for your customizations */ 8 | .phx-no-feedback.invalid-feedback, 9 | .phx-no-feedback .invalid-feedback { 10 | display: none; 11 | } 12 | 13 | .phx-click-loading { 14 | opacity: 0.5; 15 | transition: opacity 1s ease-out; 16 | } 17 | 18 | .phx-disconnected{ 19 | cursor: wait; 20 | } 21 | .phx-disconnected *{ 22 | pointer-events: none; 23 | } 24 | 25 | .phx-modal { 26 | opacity: 1!important; 27 | position: fixed; 28 | z-index: 1; 29 | left: 0; 30 | top: 0; 31 | width: 100%; 32 | height: 100%; 33 | overflow: auto; 34 | background-color: rgb(0,0,0); 35 | background-color: rgba(0,0,0,0.4); 36 | } 37 | 38 | .phx-modal-content { 39 | background-color: #fefefe; 40 | margin: 15% auto; 41 | padding: 20px; 42 | border: 1px solid #888; 43 | width: 80%; 44 | } 45 | 46 | .phx-modal-close { 47 | color: #aaa; 48 | float: right; 49 | font-size: 28px; 50 | font-weight: bold; 51 | } 52 | 53 | .phx-modal-close:hover, 54 | .phx-modal-close:focus { 55 | color: black; 56 | text-decoration: none; 57 | cursor: pointer; 58 | } 59 | 60 | 61 | /* Alerts and form errors */ 62 | .alert { 63 | padding: 15px; 64 | margin-bottom: 20px; 65 | border: 1px solid transparent; 66 | border-radius: 4px; 67 | } 68 | .alert-info { 69 | color: #31708f; 70 | background-color: #d9edf7; 71 | border-color: #bce8f1; 72 | } 73 | .alert-warning { 74 | color: #8a6d3b; 75 | background-color: #fcf8e3; 76 | border-color: #faebcc; 77 | } 78 | .alert-danger { 79 | color: #a94442; 80 | background-color: #f2dede; 81 | border-color: #ebccd1; 82 | } 83 | .alert p { 84 | margin-bottom: 0; 85 | } 86 | .alert:empty { 87 | display: none; 88 | } 89 | .invalid-feedback { 90 | color: #a94442; 91 | display: block; 92 | margin: -1rem 0 2rem; 93 | } 94 | // OUR STYLES 95 | body { 96 | font-family: 'Lato', 'Helvetica', 'Arial'; 97 | margin: 0; 98 | background: #e1dfe8; 99 | } 100 | 101 | header { 102 | background: #007AA1; 103 | border-bottom: 1px solid #007AA1; 104 | padding: 1em 0em 105 | } 106 | 107 | .container { 108 | //min-width: 60vw; 109 | display: flex; 110 | justify-content: center; 111 | } 112 | 113 | #logo { 114 | height: 80px 115 | } 116 | 117 | .chart_container { 118 | display: inline-block; 119 | padding: 20px; 120 | background-color: white; 121 | border-radius: 20px; 122 | //height: 20vw; 123 | box-shadow: 5px 5px 10px 0px rgba(152,141,161,0.15); 124 | } 125 | 126 | .chart_parent { 127 | width: 100%; 128 | margin: 0 auto; 129 | } 130 | 131 | .controls { 132 | display: flex; /* or inline-flex */ 133 | flex-direction: row; 134 | vertical-align: middle; 135 | 136 | margin: 5px auto; 137 | } 138 | 139 | .controls > * + * { 140 | margin-left: 5px; 141 | } 142 | -------------------------------------------------------------------------------- /assets/css/phoenix.css: -------------------------------------------------------------------------------- 1 | /* Includes some default style for the starter application. 2 | * This can be safely deleted to start fresh. 3 | */ 4 | 5 | /* Milligram v1.3.0 https://milligram.github.io 6 | * Copyright (c) 2017 CJ Patoilo Licensed under the MIT license 7 | */ 8 | 9 | *,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='email'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],textarea,select{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem;width:100%}input[type='email']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{-ms-grid-row-align:center;align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem;text-align:left}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right} 10 | 11 | /* General style */ 12 | h1{font-size: 3.6rem; line-height: 1.25} 13 | h2{font-size: 2.8rem; line-height: 1.3} 14 | h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} 15 | h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} 16 | h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} 17 | h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} 18 | pre{padding: 1em;} 19 | 20 | /* .container{ 21 | margin: 0 auto; 22 | max-width: 60vw; 23 | padding: 0 2.0rem; 24 | position: relative; 25 | width: 100%; 26 | } */ 27 | 28 | select { 29 | width: auto; 30 | } 31 | 32 | /* Phoenix promo and logo */ 33 | .phx-hero { 34 | text-align: center; 35 | border-bottom: 1px solid #e3e3e3; 36 | background: #eee; 37 | border-radius: 6px; 38 | padding: 3em 3em 1em; 39 | margin-bottom: 3rem; 40 | font-weight: 200; 41 | font-size: 120%; 42 | } 43 | .phx-hero input { 44 | background: #ffffff; 45 | } 46 | .phx-logo { 47 | min-width: 300px; 48 | margin: 1rem; 49 | display: block; 50 | } 51 | .phx-logo img { 52 | width: auto; 53 | display: block; 54 | } 55 | 56 | /* Headers */ 57 | header { 58 | width: 100%; 59 | background: #fdfdfd; 60 | border-bottom: 1px solid #eaeaea; 61 | margin-bottom: 2rem; 62 | } 63 | header section { 64 | align-items: center; 65 | display: flex; 66 | flex-direction: column; 67 | justify-content: space-between; 68 | } 69 | header section :first-child { 70 | order: 2; 71 | } 72 | header section :last-child { 73 | order: 1; 74 | } 75 | header nav ul, 76 | header nav li { 77 | margin: 0; 78 | padding: 0; 79 | display: block; 80 | text-align: right; 81 | white-space: nowrap; 82 | } 83 | header nav ul { 84 | margin: 1rem; 85 | margin-top: 0; 86 | } 87 | header nav a { 88 | display: block; 89 | } 90 | 91 | @media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ 92 | header section { 93 | flex-direction: row; 94 | } 95 | header nav ul { 96 | margin: 1rem; 97 | } 98 | .phx-logo { 99 | flex-basis: 527px; 100 | margin: 2rem 1rem; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /assets/js/app.js: -------------------------------------------------------------------------------- 1 | // We need to import the CSS so that webpack will load it. 2 | // The MiniCssExtractPlugin is used to separate it out into 3 | // its own CSS file. 4 | import "../css/app.scss" 5 | 6 | // webpack automatically bundles all modules in your 7 | // entry points. Those entry points can be configured 8 | // in "webpack.config.js". 9 | // 10 | // Import deps with the dep name or local files with a relative path, for example: 11 | // 12 | // import {Socket} from "phoenix" 13 | // import socket from "./socket" 14 | // 15 | import "phoenix_html" 16 | import { Socket } from "phoenix" 17 | import NProgress from "nprogress" 18 | import { LiveSocket } from "phoenix_live_view" 19 | import { ChartData } from "./chart" 20 | let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") 21 | 22 | let Hooks = { 23 | ChartData: ChartData 24 | } 25 | 26 | let liveSocket = new LiveSocket("/live", Socket, { hooks: Hooks, params: { _csrf_token: csrfToken } }) 27 | 28 | // Show progress bar on live navigation and form submits 29 | window.addEventListener("phx:page-loading-start", info => NProgress.start()) 30 | window.addEventListener("phx:page-loading-stop", info => NProgress.done()) 31 | 32 | // connect if there are any LiveViews on the page 33 | liveSocket.connect() 34 | 35 | // expose liveSocket on window for web console debug logs and latency simulation: 36 | // >> liveSocket.enableDebug() 37 | // >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session 38 | // >> liveSocket.disableLatencySim() 39 | window.liveSocket = liveSocket 40 | 41 | -------------------------------------------------------------------------------- /assets/js/chart.js: -------------------------------------------------------------------------------- 1 | import uPlot from 'uplot' 2 | 3 | let chart = null; 4 | 5 | function paths(u, sidx, i0, i1) { 6 | const s = u.series[sidx]; 7 | const xdata = u.data[0]; 8 | const ydata = u.data[sidx]; 9 | const scaleX = 'x'; 10 | const scaleY = s.scale; 11 | 12 | const stroke = new Path2D(); 13 | 14 | const x_width = Math.abs((u.valToPos(xdata[0], scaleX, true) - u.valToPos(xdata[1], scaleX, true)) / 2); 15 | 16 | stroke.moveTo( 17 | Math.round(u.valToPos(xdata[0], scaleX, true)), 18 | Math.round(u.valToPos(ydata[0], scaleY, true)) 19 | ); 20 | 21 | for (let i = i0; i < i1; i++) { 22 | let x0 = Math.round(u.valToPos(xdata[i], scaleX, true)); 23 | let y0 = Math.round(u.valToPos(ydata[i], scaleY, true)); 24 | let x1 = Math.round(u.valToPos(xdata[i + 1], scaleX, true)); 25 | let y1 = Math.round(u.valToPos(ydata[i + 1], scaleY, true)); 26 | 27 | stroke.lineTo(x0 - x_width, y0); 28 | stroke.lineTo(x1 - x_width, y0); 29 | 30 | if (i == i1 - 1) { 31 | stroke.lineTo(x1 - x_width, y1); 32 | stroke.lineTo(x1, y1); 33 | } 34 | } 35 | 36 | const fill = new Path2D(stroke); 37 | 38 | let minY = Math.round(u.valToPos(u.scales[scaleY].min, scaleY, true)); 39 | let minX = Math.round(u.valToPos(u.scales[scaleX].min, scaleX, true)); 40 | let maxX = Math.round(u.valToPos(u.scales[scaleX].max, scaleX, true)); 41 | 42 | fill.lineTo(maxX, minY); 43 | fill.lineTo(minX, minY); 44 | 45 | return { 46 | stroke, 47 | fill, 48 | }; 49 | } 50 | 51 | function safe_to_fixed(number, decimals) { 52 | return number && number.toFixed(decimals) 53 | } 54 | 55 | function create_chart(data, scale) { 56 | let rect = { width: window.innerWidth * 0.6, height: 400 }; 57 | 58 | let scaler = null; 59 | if (scale == "Linear") { 60 | scaler = (x) => x && x 61 | } else if (scale == "Log10") { 62 | scaler = (x) => x && Math.pow(10, x) 63 | } else if (scale == "Log2") { 64 | scaler = (x) => x && Math.pow(2, x) 65 | } 66 | let existing = document.getElementById("chart1"); 67 | existing && existing.remove(); 68 | 69 | let opts = { 70 | title: "Web Request Response Time [ms]", 71 | id: "chart1", 72 | class: "my-chart", 73 | width: rect.width, 74 | height: rect.height, 75 | labelSize: 10, 76 | labelFont: "bold 8px Arial", 77 | ticks: { show: false }, 78 | points: { show: false }, 79 | font: "8px Arial", 80 | series: [ 81 | { value: '{YYYY}-{MM}-{DD} {HH}:{mm}:{ss}' }, 82 | { 83 | label: "P99", 84 | stroke: "rgb(155, 214, 206)", 85 | value: (self, rawValue) => safe_to_fixed(scaler(rawValue), 3) + "ms", 86 | fill: "rgb(155, 214, 206, 0.5 )", 87 | paths: paths, 88 | scale: "ms" 89 | }, 90 | { 91 | label: "P90", 92 | stroke: "rgb(79, 169, 184)", 93 | value: (self, rawValue) => safe_to_fixed(scaler(rawValue), 3) + "ms", 94 | fill: "rgb(79, 169, 184, 0.5)", 95 | paths: paths, 96 | scale: "ms" 97 | }, 98 | { 99 | label: "P50", 100 | stroke: "rgb(2, 88, 115)", 101 | value: (self, rawValue) => safe_to_fixed(scaler(rawValue), 3) + "ms", 102 | fill: "rgb(2, 88, 115, 0.5)", 103 | paths: paths, 104 | scale: "ms" 105 | }, 106 | { 107 | label: "Throughput", 108 | ke: "rgb(30, 30, 30)", 109 | value: (self, rawValue) => scaler(rawValue) + "rpm", 110 | scale: "rpm" 111 | } 112 | ], 113 | axes: [ 114 | {}, 115 | { 116 | scale: "ms", 117 | grid: { show: false }, 118 | values: (u, vals, space) => vals.map((val) => safe_to_fixed(scaler(val), 2) + "ms") 119 | }, 120 | { 121 | side: 1, 122 | values: (u, vals, space) => vals.map((val) => safe_to_fixed(scaler(val), 2) + "reqs"), 123 | scale: "reqs", 124 | grid: { show: false }, 125 | }, 126 | ] 127 | }; 128 | 129 | chart = new uPlot(opts, data, document.getElementById("chart")); 130 | } 131 | 132 | let scale = ""; 133 | 134 | export const ChartData = { 135 | mounted() { 136 | scale = JSON.parse(this.el.dataset.scale); 137 | let quantile_data = JSON.parse(this.el.dataset.quantile); 138 | create_chart(quantile_data, scale); 139 | }, 140 | updated() { 141 | let new_scale = JSON.parse(this.el.dataset.scale); 142 | if (scale == new_scale) { 143 | let quantile_data = JSON.parse(this.el.dataset.quantile); 144 | chart.setData(quantile_data, scale); 145 | } else { 146 | this.mounted(); 147 | } 148 | } 149 | } -------------------------------------------------------------------------------- /assets/js/heatmap.js: -------------------------------------------------------------------------------- 1 | import uPlot from 'uplot' 2 | 3 | let chart = null; 4 | 5 | function draw(u) { 6 | console.log(["draw", u]) 7 | } 8 | 9 | function heatmapPlugin() { 10 | return { 11 | hooks: { 12 | draw: u => { 13 | console.log("getting here too"); 14 | } 15 | } 16 | } 17 | } 18 | 19 | function paths(u, sidx, i0, i1) { 20 | const s = u.series[sidx]; 21 | const xdata = u.data[0]; 22 | const ydata = u.data[sidx]; 23 | const scaleX = 'x'; 24 | const scaleY = s.scale; 25 | 26 | const stroke = new Path2D(); 27 | 28 | const x_width = Math.abs((u.valToPos(xdata[0], scaleX, true) - u.valToPos(xdata[1], scaleX, true)) / 2); 29 | 30 | stroke.moveTo( 31 | Math.round(u.valToPos(xdata[0], scaleX, true)), 32 | Math.round(u.valToPos(ydata[0], scaleY, true)) 33 | ); 34 | 35 | for (let i = i0; i < i1; i++) { 36 | let x0 = Math.round(u.valToPos(xdata[i], scaleX, true)); 37 | let y0 = Math.round(u.valToPos(ydata[i], scaleY, true)); 38 | let x1 = Math.round(u.valToPos(xdata[i + 1], scaleX, true)); 39 | let y1 = Math.round(u.valToPos(ydata[i + 1], scaleY, true)); 40 | 41 | stroke.lineTo(x0 - x_width, y0); 42 | stroke.lineTo(x1 - x_width, y0); 43 | 44 | if (i == i1 - 1) { 45 | stroke.lineTo(x1 - x_width, y1); 46 | stroke.lineTo(x1, y1); 47 | } 48 | } 49 | 50 | const fill = new Path2D(stroke); 51 | 52 | let minY = Math.round(u.valToPos(u.scales[scaleY].min, scaleY, true)); 53 | let minX = Math.round(u.valToPos(u.scales[scaleX].min, scaleX, true)); 54 | let maxX = Math.round(u.valToPos(u.scales[scaleX].max, scaleX, true)); 55 | 56 | fill.lineTo(maxX, minY); 57 | fill.lineTo(minX, minY); 58 | 59 | return { 60 | stroke, 61 | fill, 62 | }; 63 | } 64 | 65 | function create_chart(raw) { 66 | //let rect = (document.getElementById("chart_parent").getBoundingClientRect()); 67 | let rect = { width: window.innerWidth * 0.6, height: 400 }; 68 | 69 | let data = raw; 70 | // let data = [ 71 | // raw[0], 72 | // // raw[1].map(vals => vals[0]), 73 | // // raw[1].map(vals => vals[vals.length - 1]), 74 | // raw[1] 75 | // ]; 76 | 77 | console.log(data) 78 | 79 | let opts = { 80 | title: "Web Request Response Time [ms]", 81 | id: "heatmap-chart", 82 | class: "my-chart", 83 | width: rect.width, 84 | height: rect.height, 85 | plugins: [ 86 | heatmapPlugin() 87 | ], 88 | labelSize: 10, 89 | labelFont: "bold 8px Arial", 90 | ticks: { show: false }, 91 | points: { show: false }, 92 | font: "8px Arial", 93 | series: [ 94 | { value: '{YYYY}-{MM}-{DD} {HH}:{mm}:{ss}' }, 95 | { 96 | label: "Requests", 97 | ke: "rgb(30, 30, 30)", 98 | value: (self, rawValue) => rawValue + "rpm", 99 | paths: () => null, 100 | draw: draw, 101 | points: {show: false} 102 | } 103 | ], 104 | }; 105 | 106 | console.log(opts); 107 | 108 | chart = new uPlot(opts, data, document.getElementById("heatmap")); 109 | } 110 | 111 | export const HeatmapData = { 112 | mounted() { 113 | // mounted stuff here. 114 | console.log(JSON.parse(this.el.dataset.heatmap)); 115 | create_chart(JSON.parse(this.el.dataset.heatmap)); 116 | }, 117 | updated() { 118 | chart.setData(JSON.parse(this.el.dataset.heatmap)); 119 | } 120 | } 121 | 122 | 123 | // function rawData(xCount, ySeriesCount, yCountMin, yCountMax, yMin, yMax) { 124 | // xCount = xCount || 100; 125 | // ySeriesCount = ySeriesCount || 1; 126 | 127 | // // 50-300 samples per x 128 | // yCountMin = yCountMin || 200; 129 | // yCountMax = yCountMax || 500; 130 | 131 | // // y values in 0 - 1000 range 132 | // yMin = yMin || 5; 133 | // yMax = yMax || 1000; 134 | 135 | // let data = [ 136 | // [], 137 | // ...Array(ySeriesCount).fill(null).map(_ => []), 138 | // ]; 139 | 140 | // let now = Math.round(new Date() / 1e3); 141 | 142 | // let finalCount = 0; 143 | 144 | // for (let xi = 0; xi < xCount; xi++) { 145 | // data[0][xi] = now++; 146 | 147 | // for (let si = 1; si <= ySeriesCount; si++) { 148 | // let yCount = randInt(yCountMin, yCountMax); 149 | 150 | // let vals = data[si][xi] = []; 151 | 152 | // while (yCount-- > 0) { 153 | // // vals.push(Math.round(randn_bm(yMin, yMax, 3))); 154 | // vals.push(Math.max(randomSkewNormal(Math.random, 30, 30, 3), yMin)); 155 | // finalCount++; 156 | // } 157 | 158 | // vals.sort((a, b) => a - b); 159 | // } 160 | // } 161 | 162 | // console.log(finalCount); 163 | 164 | // return data; 165 | // } 166 | 167 | // function incrRound(num, incr) { 168 | // return Math.round(num/incr)*incr; 169 | // } 170 | 171 | // function incrRoundUp(num, incr) { 172 | // return Math.ceil(num/incr)*incr; 173 | // } 174 | 175 | // function incrRoundDn(num, incr) { 176 | // return Math.floor(num/incr)*incr; 177 | // } 178 | 179 | // function aggData(data, incr) { 180 | // let data2 = [ 181 | // data[0], 182 | // [], 183 | // [], 184 | // ]; 185 | 186 | // data[1].forEach((vals, xi) => { 187 | // let _aggs = []; 188 | // let _counts = []; 189 | 190 | // let _curVal = incrRoundUp(vals[0], incr); 191 | // let _curCount = 0; 192 | 193 | // vals.forEach(v => { 194 | // v = incrRoundUp(v, incr); 195 | 196 | // if (v == _curVal) 197 | // _curCount++; 198 | // else { 199 | // _aggs.push(_curVal); 200 | // _counts.push(_curCount); 201 | 202 | // _curVal = v; 203 | // _curCount = 1; 204 | // } 205 | // }); 206 | 207 | // _aggs.push(_curVal); 208 | // _counts.push(_curCount); 209 | 210 | // data2[1][xi] = _aggs; 211 | // data2[2][xi] = _counts; 212 | // }); 213 | 214 | // return data2; 215 | // } 216 | 217 | // console.time("rawData"); 218 | // let raw = rawData(); 219 | // console.timeEnd("rawData"); 220 | // // console.log(raw); 221 | 222 | // let data = [ 223 | // raw[0], 224 | // raw[1].map(vals => vals[0]), 225 | // raw[1].map(vals => vals[vals.length - 1]), 226 | // raw[1], 227 | // ]; 228 | 229 | // function heatmapPlugin() { 230 | // return { 231 | // hooks: { 232 | // draw: u => { 233 | // const { ctx, data } = u; 234 | 235 | // let yData = data[3]; 236 | 237 | // yData.forEach((yVals, xi) => { 238 | // let xPos = Math.round(u.valToPos(data[0][xi], 'x', true)); 239 | 240 | // yVals.forEach(yVal => { 241 | // let yPos = Math.round(u.valToPos(yVal, 'y', true)); 242 | // ctx.fillStyle = "rgba(255,0,0,0.4)"; 243 | // ctx.fillRect( 244 | // xPos - 4, 245 | // yPos, 246 | // 10, 247 | // 1, 248 | // ); 249 | // }); 250 | // }); 251 | // } 252 | // } 253 | // }; 254 | // } 255 | 256 | // const opts = { 257 | // width: 1800, 258 | // height: 600, 259 | // title: "Latency Heatmap (~20k)", 260 | // plugins: [ 261 | // heatmapPlugin(), 262 | // ], 263 | // cursor: { 264 | // drag: { 265 | // y: true, 266 | // }, 267 | // points: { 268 | // show: false 269 | // } 270 | // }, 271 | // series: [ 272 | // {}, 273 | // { 274 | // paths: () => null, 275 | // points: {show: false}, 276 | // }, 277 | // { 278 | // paths: () => null, 279 | // points: {show: false}, 280 | // }, 281 | // ], 282 | // }; 283 | 284 | // let u = new uPlot(opts, data, document.body); 285 | 286 | 287 | // const bucketIncr = 2; 288 | 289 | // // console.time("aggData"); 290 | // let agg = aggData(raw, bucketIncr); 291 | // // console.timeEnd("aggData"); 292 | // // console.log(agg); 293 | 294 | // let data2 = [ 295 | // agg[0], 296 | // raw[1].map(vals => vals[0]), 297 | // raw[1].map(vals => vals[vals.length - 1]), 298 | // agg[1], 299 | // agg[2], 300 | // ]; 301 | 302 | // function heatmapPlugin2() { 303 | // // let global min/max 304 | // function fillStyle(count, minCount, maxCount) { 305 | // // console.log(val); 306 | // return `hsla(${180 + count/maxCount * 180}, 80%, 50%, 1)`; 307 | // } 308 | 309 | // return { 310 | // hooks: { 311 | // draw: u => { 312 | // const { ctx, data } = u; 313 | 314 | // let yData = data[3]; 315 | // let yQtys = data[4]; 316 | // /* 317 | // let maxCount = -Infinity; 318 | // let minCount = Infinity; 319 | 320 | // yQtys.forEach(qtys => { 321 | // maxCount = Math.max(maxCount, Math.max.apply(null, qtys)); 322 | // minCount = Math.min(minCount, Math.min.apply(null, qtys)); 323 | // }); 324 | 325 | // console.log(maxCount, minCount); 326 | // */ 327 | 328 | // // pre-calc rect height since we know the aggregation bucket 329 | // let yHgt = Math.floor(u.valToPos(bucketIncr, 'y', true) - u.valToPos(0, 'y', true)); 330 | 331 | // yData.forEach((yVals, xi) => { 332 | // let xPos = Math.floor(u.valToPos(data[0][xi], 'x', true)); 333 | 334 | // let maxCount = yQtys[xi].reduce((acc, val) => Math.max(val, acc), -Infinity); 335 | 336 | // yVals.forEach((yVal, yi) => { 337 | // let yPos = Math.floor(u.valToPos(yVal, 'y', true)); 338 | 339 | // // ctx.fillStyle = fillStyle(yQtys[xi][yi], minCount, maxCount); 340 | // ctx.fillStyle = fillStyle(yQtys[xi][yi], 1, maxCount); 341 | // ctx.fillRect( 342 | // xPos - 4, 343 | // yPos, 344 | // 10, 345 | // yHgt, 346 | // ); 347 | // }); 348 | // }); 349 | // } 350 | // } 351 | // }; 352 | // } 353 | 354 | // const opts2 = { 355 | // width: 1800, 356 | // height: 600, 357 | // title: "Latency Heatmap Aggregated 10ms (~20k)", 358 | // plugins: [ 359 | // heatmapPlugin2(), 360 | // ], 361 | // cursor: { 362 | // drag: { 363 | // y: true, 364 | // }, 365 | // points: { 366 | // show: false 367 | // } 368 | // }, 369 | // series: [ 370 | // {}, 371 | // { 372 | // paths: () => null, 373 | // points: {show: false}, 374 | // }, 375 | // { 376 | // paths: () => null, 377 | // points: {show: false}, 378 | // }, 379 | // ], 380 | // }; 381 | 382 | // let u2 = new uPlot(opts2, data2, document.body); 383 | -------------------------------------------------------------------------------- /assets/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "repository": {}, 3 | "description": " ", 4 | "license": "MIT", 5 | "scripts": { 6 | "deploy": "webpack --mode production", 7 | "watch": "webpack --mode development --watch" 8 | }, 9 | "dependencies": { 10 | "nprogress": "^0.2.0", 11 | "phoenix": "file:../deps/phoenix", 12 | "phoenix_html": "file:../deps/phoenix_html", 13 | "phoenix_live_view": "file:../deps/phoenix_live_view", 14 | "uplot": "^1.1.2" 15 | }, 16 | "devDependencies": { 17 | "@babel/core": "^7.0.0", 18 | "@babel/preset-env": "^7.0.0", 19 | "babel-loader": "^8.0.0", 20 | "copy-webpack-plugin": "^5.1.1", 21 | "css-loader": "^3.4.2", 22 | "sass-loader": "^8.0.2", 23 | "node-sass": "^4.13.1", 24 | "hard-source-webpack-plugin": "^0.13.1", 25 | "mini-css-extract-plugin": "^0.9.0", 26 | "optimize-css-assets-webpack-plugin": "^5.0.1", 27 | "terser-webpack-plugin": "^2.3.2", 28 | "webpack": "4.41.5", 29 | "webpack-cli": "^3.3.2" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /assets/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/assets/static/favicon.ico -------------------------------------------------------------------------------- /assets/static/images/phoenix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/assets/static/images/phoenix.png -------------------------------------------------------------------------------- /assets/static/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /assets/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const glob = require('glob'); 3 | const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); 4 | const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 5 | const TerserPlugin = require('terser-webpack-plugin'); 6 | const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); 7 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 8 | 9 | module.exports = (env, options) => { 10 | const devMode = options.mode !== 'production'; 11 | 12 | return { 13 | optimization: { 14 | minimizer: [ 15 | new TerserPlugin({ cache: true, parallel: true, sourceMap: devMode }), 16 | new OptimizeCSSAssetsPlugin({}) 17 | ] 18 | }, 19 | entry: { 20 | 'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js']) 21 | }, 22 | output: { 23 | filename: '[name].js', 24 | path: path.resolve(__dirname, '../priv/static/js'), 25 | publicPath: '/js/' 26 | }, 27 | devtool: devMode ? 'eval-cheap-module-source-map' : undefined, 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.js$/, 32 | exclude: /node_modules/, 33 | use: { 34 | loader: 'babel-loader' 35 | } 36 | }, 37 | { 38 | test: /\.[s]?css$/, 39 | use: [ 40 | MiniCssExtractPlugin.loader, 41 | 'css-loader', 42 | 'sass-loader', 43 | ], 44 | } 45 | ] 46 | }, 47 | plugins: [ 48 | new MiniCssExtractPlugin({ filename: '../css/app.css' }), 49 | new CopyWebpackPlugin([{ from: 'static/', to: '../' }]) 50 | ] 51 | .concat(devMode ? [new HardSourceWebpackPlugin()] : []) 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | # 4 | # This configuration file is loaded before any dependency and 5 | # is restricted to this project. 6 | 7 | # General application configuration 8 | use Mix.Config 9 | 10 | # Configures the endpoint 11 | config :spotlight, SpotlightWeb.Endpoint, 12 | url: [host: "localhost"], 13 | secret_key_base: "uxyF5ASq97hlt+1S57AqIYwLUmpeOVD5rfa6CrDwWJF96S5vA4zMaw961N7hh7xI", 14 | render_errors: [view: SpotlightWeb.ErrorView, accepts: ~w(html json), layout: false], 15 | pubsub_server: Spotlight.PubSub, 16 | live_view: [signing_salt: "KXDRC1tA"] 17 | 18 | # Configures Elixir's Logger 19 | config :logger, :console, 20 | format: "$time $metadata[$level] $message\n", 21 | metadata: [:request_id] 22 | 23 | # Use Jason for JSON parsing in Phoenix 24 | config :phoenix, :json_library, Jason 25 | 26 | # Import environment specific config. This must remain at the bottom 27 | # of this file so it overrides the configuration defined above. 28 | import_config "#{Mix.env()}.exs" 29 | -------------------------------------------------------------------------------- /config/dev.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | # For development, we disable any cache and enable 4 | # debugging and code reloading. 5 | # 6 | # The watchers configuration can be used to run external 7 | # watchers to your application. For example, we use it 8 | # with webpack to recompile .js and .css sources. 9 | config :spotlight, SpotlightWeb.Endpoint, 10 | http: [port: 4000], 11 | debug_errors: true, 12 | code_reloader: true, 13 | check_origin: false, 14 | watchers: [ 15 | node: [ 16 | "node_modules/webpack/bin/webpack.js", 17 | "--mode", 18 | "development", 19 | "--watch-stdin", 20 | cd: Path.expand("../assets", __DIR__) 21 | ] 22 | ] 23 | 24 | # ## SSL Support 25 | # 26 | # In order to use HTTPS in development, a self-signed 27 | # certificate can be generated by running the following 28 | # Mix task: 29 | # 30 | # mix phx.gen.cert 31 | # 32 | # Note that this task requires Erlang/OTP 20 or later. 33 | # Run `mix help phx.gen.cert` for more information. 34 | # 35 | # The `http:` config above can be replaced with: 36 | # 37 | # https: [ 38 | # port: 4001, 39 | # cipher_suite: :strong, 40 | # keyfile: "priv/cert/selfsigned_key.pem", 41 | # certfile: "priv/cert/selfsigned.pem" 42 | # ], 43 | # 44 | # If desired, both `http:` and `https:` keys can be 45 | # configured to run both http and https servers on 46 | # different ports. 47 | 48 | # Watch static and templates for browser reloading. 49 | config :spotlight, SpotlightWeb.Endpoint, 50 | live_reload: [ 51 | patterns: [ 52 | ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", 53 | ~r"priv/gettext/.*(po)$", 54 | ~r"lib/spotlight_web/(live|views)/.*(ex)$", 55 | ~r"lib/spotlight_web/templates/.*(eex)$" 56 | ] 57 | ] 58 | 59 | # Do not include metadata nor timestamps in development logs 60 | config :logger, :console, format: "[$level] $message\n" 61 | 62 | # Set a higher stacktrace during development. Avoid configuring such 63 | # in production as building large stacktraces may be expensive. 64 | config :phoenix, :stacktrace_depth, 20 65 | 66 | # Initialize plugs at runtime for faster development compilation 67 | config :phoenix, :plug_init_mode, :runtime 68 | -------------------------------------------------------------------------------- /config/prod.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | # For production, don't forget to configure the url host 4 | # to something meaningful, Phoenix uses this information 5 | # when generating URLs. 6 | # 7 | # Note we also include the path to a cache manifest 8 | # containing the digested version of static files. This 9 | # manifest is generated by the `mix phx.digest` task, 10 | # which you should run after static files are built and 11 | # before starting your production server. 12 | config :spotlight, SpotlightWeb.Endpoint, 13 | url: [host: "example.com", port: 80], 14 | cache_static_manifest: "priv/static/cache_manifest.json" 15 | 16 | # Do not print debug messages in production 17 | config :logger, level: :info 18 | 19 | # ## SSL Support 20 | # 21 | # To get SSL working, you will need to add the `https` key 22 | # to the previous section and set your `:url` port to 443: 23 | # 24 | # config :spotlight, SpotlightWeb.Endpoint, 25 | # ... 26 | # url: [host: "example.com", port: 443], 27 | # https: [ 28 | # port: 443, 29 | # cipher_suite: :strong, 30 | # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), 31 | # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), 32 | # transport_options: [socket_opts: [:inet6]] 33 | # ] 34 | # 35 | # The `cipher_suite` is set to `:strong` to support only the 36 | # latest and more secure SSL ciphers. This means old browsers 37 | # and clients may not be supported. You can set it to 38 | # `:compatible` for wider support. 39 | # 40 | # `:keyfile` and `:certfile` expect an absolute path to the key 41 | # and cert in disk or a relative path inside priv, for example 42 | # "priv/ssl/server.key". For all supported SSL configuration 43 | # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 44 | # 45 | # We also recommend setting `force_ssl` in your endpoint, ensuring 46 | # no data is ever sent via http, always redirecting to https: 47 | # 48 | # config :spotlight, SpotlightWeb.Endpoint, 49 | # force_ssl: [hsts: true] 50 | # 51 | # Check `Plug.SSL` for all available options in `force_ssl`. 52 | 53 | # Finally import the config/prod.secret.exs which loads secrets 54 | # and configuration from environment variables. 55 | import_config "prod.secret.exs" 56 | -------------------------------------------------------------------------------- /config/prod.secret.exs: -------------------------------------------------------------------------------- 1 | # In this file, we load production configuration and secrets 2 | # from environment variables. You can also hardcode secrets, 3 | # although such is generally not recommended and you have to 4 | # remember to add this file to your .gitignore. 5 | use Mix.Config 6 | 7 | secret_key_base = 8 | System.get_env("SECRET_KEY_BASE") || 9 | raise """ 10 | environment variable SECRET_KEY_BASE is missing. 11 | You can generate one by calling: mix phx.gen.secret 12 | """ 13 | 14 | config :spotlight, SpotlightWeb.Endpoint, 15 | http: [ 16 | port: String.to_integer(System.get_env("PORT") || "4000"), 17 | transport_options: [socket_opts: [:inet6]] 18 | ], 19 | secret_key_base: secret_key_base 20 | 21 | # ## Using releases (Elixir v1.9+) 22 | # 23 | # If you are doing OTP releases, you need to instruct Phoenix 24 | # to start each relevant endpoint: 25 | # 26 | # config :spotlight, SpotlightWeb.Endpoint, server: true 27 | # 28 | # Then you can assemble a release by calling `mix release`. 29 | # See `mix help release` for more information. 30 | -------------------------------------------------------------------------------- /config/test.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | # We don't run a server during test. If one is required, 4 | # you can enable the server option below. 5 | config :spotlight, SpotlightWeb.Endpoint, 6 | http: [port: 4002], 7 | server: false 8 | 9 | # Print only warnings and errors during test 10 | config :logger, level: :warn 11 | -------------------------------------------------------------------------------- /img/linearscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/img/linearscale.png -------------------------------------------------------------------------------- /img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/img/logo.png -------------------------------------------------------------------------------- /img/logscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/img/logscale.png -------------------------------------------------------------------------------- /img/logscale2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spawnfest/beamwork/a206f185f04323e34376b4d9193bc5bdd2ead49b/img/logscale2.png -------------------------------------------------------------------------------- /lib/spotlight.ex: -------------------------------------------------------------------------------- 1 | defmodule Spotlight do 2 | @moduledoc """ 3 | Spotlight keeps the contexts that define your domain 4 | and business logic. 5 | 6 | Contexts are also responsible for managing your data, regardless 7 | if it comes from the database, an external API or others. 8 | """ 9 | end 10 | -------------------------------------------------------------------------------- /lib/spotlight/application.ex: -------------------------------------------------------------------------------- 1 | defmodule Spotlight.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | def start(_type, _args) do 9 | children = [ 10 | # Start the Telemetry supervisor 11 | SpotlightWeb.Telemetry, 12 | # Start the PubSub system 13 | {Phoenix.PubSub, name: Spotlight.PubSub}, 14 | # Start the Endpoint (http/https) 15 | SpotlightWeb.Endpoint, 16 | Spotlight.RequestTimeCollector 17 | # Start a worker by calling: Spotlight.Worker.start_link(arg) 18 | # {Spotlight.Worker, arg} 19 | ] 20 | 21 | # See https://hexdocs.pm/elixir/Supervisor.html 22 | # for other strategies and supported options 23 | opts = [strategy: :one_for_one, name: Spotlight.Supervisor] 24 | Supervisor.start_link(children, opts) 25 | end 26 | 27 | # Tell Phoenix to update the endpoint configuration 28 | # whenever the application is updated. 29 | def config_change(changed, _new, removed) do 30 | SpotlightWeb.Endpoint.config_change(changed, removed) 31 | :ok 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/spotlight/request_time_collector.ex: -------------------------------------------------------------------------------- 1 | defmodule Spotlight.RequestTimeCollector do 2 | alias DogSketch.SimpleDog 3 | 4 | def child_spec(_) do 5 | %{ 6 | id: __MODULE__, 7 | start: {__MODULE__, :start_link, []} 8 | } 9 | end 10 | 11 | def start_link() do 12 | GenServer.start_link(__MODULE__, [], name: __MODULE__) 13 | end 14 | 15 | @seconds_to_keep 600 16 | @max_error 0.04 17 | 18 | def init(config) do 19 | seconds_to_keep = Keyword.get(config, :seconds_to_keep, @seconds_to_keep) 20 | max_error = Keyword.get(config, :max_error, @max_error) 21 | 22 | :telemetry.attach(__MODULE__, [:phoenix, :endpoint, :stop], &handle_metrics/4, nil) 23 | {:ok, %{keys: [], value_map: %{}, seconds_to_keep: seconds_to_keep, max_error: max_error}} 24 | end 25 | 26 | def handle_metrics([:phoenix, :endpoint, :stop], %{duration: duration}, _metadata, _config) do 27 | send( 28 | __MODULE__, 29 | {:duration, duration, System.monotonic_time(:second), System.time_offset(:second)} 30 | ) 31 | end 32 | 33 | def handle_info({:duration, duration, mono_time, time_offset}, state) do 34 | converted_duration_us = System.convert_time_unit(duration, :native, :microsecond) 35 | seconds_to_keep = state.seconds_to_keep 36 | 37 | new_state = 38 | case state.keys do 39 | [^mono_time | _] -> 40 | %{ 41 | state 42 | | value_map: 43 | Map.update!(state.value_map, mono_time, fn {dog_sketch, dt} -> 44 | {SimpleDog.insert(dog_sketch, converted_duration_us), dt} 45 | end) 46 | } 47 | 48 | keys -> 49 | sdog = 50 | SimpleDog.new(error: state.max_error) 51 | |> SimpleDog.insert(converted_duration_us) 52 | 53 | new_state = %{ 54 | state 55 | | keys: [mono_time | keys], 56 | value_map: 57 | Map.put( 58 | state.value_map, 59 | mono_time, 60 | {sdog, mono_time + time_offset} 61 | ) 62 | } 63 | 64 | new_keys = 65 | new_state.keys 66 | |> Enum.filter(fn 67 | key when key > mono_time - seconds_to_keep -> true 68 | _ -> false 69 | end) 70 | 71 | new_state = Map.put(new_state, :keys, new_keys) 72 | 73 | Map.put(new_state, :value_map, Map.take(new_state.value_map, new_state.keys)) 74 | end 75 | 76 | {:noreply, new_state} 77 | end 78 | 79 | def handle_call(:get_all, _from, state) do 80 | {:reply, Map.new(state.value_map, fn {_time, {sdog, time}} -> {time, sdog} end), state} 81 | end 82 | 83 | def get_all do 84 | GenServer.call(__MODULE__, :get_all) 85 | end 86 | 87 | def get_merged() do 88 | {results, _bad_nodes} = :rpc.multicall(__MODULE__, :get_all, []) 89 | 90 | Enum.map(results, fn 91 | {:badrpc, _reason} -> nil 92 | result -> result 93 | end) 94 | |> Enum.filter(fn x -> x end) 95 | |> Enum.reduce(%{}, fn result, acc -> 96 | Map.merge(acc, result, fn _key, s1, s2 -> 97 | SimpleDog.merge(s1, s2) 98 | end) 99 | end) 100 | end 101 | end 102 | -------------------------------------------------------------------------------- /lib/spotlight_web.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb do 2 | @moduledoc """ 3 | The entrypoint for defining your web interface, such 4 | as controllers, views, channels and so on. 5 | 6 | This can be used in your application as: 7 | 8 | use SpotlightWeb, :controller 9 | use SpotlightWeb, :view 10 | 11 | The definitions below will be executed for every view, 12 | controller, etc, so keep them short and clean, focused 13 | on imports, uses and aliases. 14 | 15 | Do NOT define functions inside the quoted expressions 16 | below. Instead, define any helper function in modules 17 | and import those modules here. 18 | """ 19 | 20 | def controller do 21 | quote do 22 | use Phoenix.Controller, namespace: SpotlightWeb 23 | 24 | import Plug.Conn 25 | import SpotlightWeb.Gettext 26 | alias SpotlightWeb.Router.Helpers, as: Routes 27 | end 28 | end 29 | 30 | def view do 31 | quote do 32 | use Phoenix.View, 33 | root: "lib/spotlight_web/templates", 34 | namespace: SpotlightWeb 35 | 36 | # Import convenience functions from controllers 37 | import Phoenix.Controller, 38 | only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] 39 | 40 | # Include shared imports and aliases for views 41 | unquote(view_helpers()) 42 | end 43 | end 44 | 45 | def live_view do 46 | quote do 47 | use Phoenix.LiveView, 48 | layout: {SpotlightWeb.LayoutView, "live.html"} 49 | 50 | unquote(view_helpers()) 51 | end 52 | end 53 | 54 | def live_component do 55 | quote do 56 | use Phoenix.LiveComponent 57 | 58 | unquote(view_helpers()) 59 | end 60 | end 61 | 62 | def router do 63 | quote do 64 | use Phoenix.Router 65 | 66 | import Plug.Conn 67 | import Phoenix.Controller 68 | import Phoenix.LiveView.Router 69 | end 70 | end 71 | 72 | def channel do 73 | quote do 74 | use Phoenix.Channel 75 | import SpotlightWeb.Gettext 76 | end 77 | end 78 | 79 | defp view_helpers do 80 | quote do 81 | # Use all HTML functionality (forms, tags, etc) 82 | use Phoenix.HTML 83 | 84 | # Import LiveView helpers (live_render, live_component, live_patch, etc) 85 | import Phoenix.LiveView.Helpers 86 | 87 | # Import basic rendering functionality (render, render_layout, etc) 88 | import Phoenix.View 89 | 90 | import SpotlightWeb.ErrorHelpers 91 | import SpotlightWeb.Gettext 92 | alias SpotlightWeb.Router.Helpers, as: Routes 93 | end 94 | end 95 | 96 | @doc """ 97 | When used, dispatch to the appropriate controller/view/etc. 98 | """ 99 | defmacro __using__(which) when is_atom(which) do 100 | apply(__MODULE__, which, []) 101 | end 102 | end 103 | -------------------------------------------------------------------------------- /lib/spotlight_web/channels/user_socket.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.UserSocket do 2 | use Phoenix.Socket 3 | 4 | ## Channels 5 | # channel "room:*", SpotlightWeb.RoomChannel 6 | 7 | # Socket params are passed from the client and can 8 | # be used to verify and authenticate a user. After 9 | # verification, you can put default assigns into 10 | # the socket that will be set for all channels, ie 11 | # 12 | # {:ok, assign(socket, :user_id, verified_user_id)} 13 | # 14 | # To deny connection, return `:error`. 15 | # 16 | # See `Phoenix.Token` documentation for examples in 17 | # performing token verification on connect. 18 | @impl true 19 | def connect(_params, socket, _connect_info) do 20 | {:ok, socket} 21 | end 22 | 23 | # Socket id's are topics that allow you to identify all sockets for a given user: 24 | # 25 | # def id(socket), do: "user_socket:#{socket.assigns.user_id}" 26 | # 27 | # Would allow you to broadcast a "disconnect" event and terminate 28 | # all active sockets and channels for a given user: 29 | # 30 | # SpotlightWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) 31 | # 32 | # Returning `nil` makes this socket anonymous. 33 | @impl true 34 | def id(_socket), do: nil 35 | end 36 | -------------------------------------------------------------------------------- /lib/spotlight_web/endpoint.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.Endpoint do 2 | use Phoenix.Endpoint, otp_app: :spotlight 3 | 4 | # The session will be stored in the cookie and signed, 5 | # this means its contents can be read but not tampered with. 6 | # Set :encryption_salt if you would also like to encrypt it. 7 | @session_options [ 8 | store: :cookie, 9 | key: "_spotlight_key", 10 | signing_salt: "dwAZ/aPx" 11 | ] 12 | 13 | socket "/socket", SpotlightWeb.UserSocket, 14 | websocket: true, 15 | longpoll: false 16 | 17 | socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] 18 | 19 | # Serve at "/" the static files from "priv/static" directory. 20 | # 21 | # You should set gzip to true if you are running phx.digest 22 | # when deploying your static files in production. 23 | plug Plug.Static, 24 | at: "/", 25 | from: :spotlight, 26 | gzip: false, 27 | only: ~w(css fonts images js favicon.ico robots.txt) 28 | 29 | # Code reloading can be explicitly enabled under the 30 | # :code_reloader configuration of your endpoint. 31 | if code_reloading? do 32 | socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket 33 | plug Phoenix.LiveReloader 34 | plug Phoenix.CodeReloader 35 | end 36 | 37 | plug Plug.RequestId 38 | plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] 39 | 40 | plug Plug.Parsers, 41 | parsers: [:urlencoded, :multipart, :json], 42 | pass: ["*/*"], 43 | json_decoder: Phoenix.json_library() 44 | 45 | plug Plug.MethodOverride 46 | plug Plug.Head 47 | plug Plug.Session, @session_options 48 | plug SpotlightWeb.Router 49 | end 50 | -------------------------------------------------------------------------------- /lib/spotlight_web/gettext.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.Gettext do 2 | @moduledoc """ 3 | A module providing Internationalization with a gettext-based API. 4 | 5 | By using [Gettext](https://hexdocs.pm/gettext), 6 | your module gains a set of macros for translations, for example: 7 | 8 | import SpotlightWeb.Gettext 9 | 10 | # Simple translation 11 | gettext("Here is the string to translate") 12 | 13 | # Plural translation 14 | ngettext("Here is the string to translate", 15 | "Here are the strings to translate", 16 | 3) 17 | 18 | # Domain-based translation 19 | dgettext("errors", "Here is the error message to translate") 20 | 21 | See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. 22 | """ 23 | use Gettext, otp_app: :spotlight 24 | end 25 | -------------------------------------------------------------------------------- /lib/spotlight_web/live/page_live.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.PageLive do 2 | use SpotlightWeb, :live_view 3 | alias DogSketch.SimpleDog 4 | 5 | @impl true 6 | def mount(_params, _session, socket) do 7 | socket = 8 | socket 9 | |> assign(quantile_data: formatted_time_series("Linear")) 10 | |> assign(:pause_action, "Pause") 11 | |> assign(:refresh_rate, 1000) 12 | |> assign(:scale, "Linear") 13 | 14 | schedule_tick(socket) 15 | 16 | {:ok, socket} 17 | end 18 | 19 | @impl true 20 | def handle_event("controls_changed", %{"rate" => rate_val, "scale" => scale_val}, socket) do 21 | socket = 22 | case rate_val do 23 | "Paused" -> 24 | assign(socket, :refresh_rate, "Paused") 25 | 26 | str_int -> 27 | {refresh_rate, _} = Integer.parse(str_int) 28 | new_socket = assign(socket, :refresh_rate, refresh_rate) 29 | if socket.assigns.refresh_rate == "Paused", do: schedule_tick(new_socket) 30 | new_socket 31 | end 32 | 33 | socket = assign(socket, :scale, scale_val) 34 | 35 | {:noreply, assign(socket, :quantile_data, formatted_time_series(socket.assigns.scale))} 36 | end 37 | 38 | @impl true 39 | def handle_info(:tick, socket) do 40 | unless is_paused?(socket) do 41 | schedule_tick(socket) 42 | end 43 | 44 | {:noreply, assign(socket, :quantile_data, formatted_time_series(socket.assigns.scale))} 45 | end 46 | 47 | defp is_paused?(socket) do 48 | case socket.assigns.refresh_rate do 49 | "Paused" -> true 50 | _ -> false 51 | end 52 | end 53 | 54 | defp schedule_tick(socket) do 55 | Process.send_after(self(), :tick, socket.assigns.refresh_rate) 56 | end 57 | 58 | defp formatted_time_series("Linear") do 59 | data = Spotlight.RequestTimeCollector.get_merged() 60 | keys = Enum.map(data, fn {ts, _} -> ts end) 61 | min_ts = Enum.min(keys, fn -> 0 end) 62 | max_ts = Enum.max(keys, fn -> 0 end) 63 | 64 | keys = Enum.map(min_ts..max_ts, fn x -> x end) 65 | 66 | [ 67 | keys, 68 | Enum.map(keys, fn ts -> 69 | get_quantile(data, ts, 0.99) 70 | end), 71 | Enum.map(keys, fn ts -> 72 | get_quantile(data, ts, 0.90) 73 | end), 74 | Enum.map(keys, fn ts -> 75 | get_quantile(data, ts, 0.50) 76 | end), 77 | Enum.map(keys, fn ts -> 78 | Map.get(data, ts, SimpleDog.new()) |> SimpleDog.count() |> ceil() 79 | end) 80 | ] 81 | end 82 | 83 | defp formatted_time_series("Log2") do 84 | [keys, p99s, p90s, p50s, counts] = formatted_time_series("Linear") 85 | 86 | [ 87 | keys, 88 | Enum.map(p99s, &safe_log2/1), 89 | Enum.map(p90s, &safe_log2/1), 90 | Enum.map(p50s, &safe_log2/1), 91 | Enum.map(counts, &safe_log2/1) 92 | ] 93 | end 94 | 95 | defp formatted_time_series("Log10") do 96 | [keys, p99s, p90s, p50s, counts] = formatted_time_series("Linear") 97 | 98 | [ 99 | keys, 100 | Enum.map(p99s, &safe_log10/1), 101 | Enum.map(p90s, &safe_log10/1), 102 | Enum.map(p50s, &safe_log10/1), 103 | Enum.map(counts, &safe_log10/1) 104 | ] 105 | end 106 | 107 | defp get_quantile(data, ts, quantile) do 108 | Map.get(data, ts, nil) 109 | |> case do 110 | nil -> 111 | nil 112 | 113 | sd -> 114 | val = SimpleDog.quantile(sd, quantile) |> ceil() 115 | val / 1000 116 | end 117 | end 118 | 119 | defp safe_log10(x) when x == 0 or is_nil(x), do: nil 120 | defp safe_log10(x), do: :math.log10(x) 121 | defp safe_log2(x) when x == 0 or is_nil(x), do: nil 122 | defp safe_log2(x), do: :math.log2(x) 123 | end 124 | -------------------------------------------------------------------------------- /lib/spotlight_web/live/page_live.html.leex: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 12 | 16 |
17 |
18 |
19 |
20 | -------------------------------------------------------------------------------- /lib/spotlight_web/router.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.Router do 2 | use SpotlightWeb, :router 3 | 4 | defmacro spotlight(path, opts \\ []) do 5 | quote bind_quoted: binding() do 6 | scope path, alias: false, as: false do 7 | import Phoenix.LiveView.Router, only: [live: 4] 8 | live "/", SpotlightWeb.PageLive, :index 9 | end 10 | end 11 | end 12 | 13 | pipeline :browser do 14 | plug :accepts, ["html"] 15 | plug :fetch_session 16 | plug :fetch_live_flash 17 | plug :put_root_layout, {SpotlightWeb.LayoutView, :root} 18 | plug :protect_from_forgery 19 | plug :put_secure_browser_headers 20 | end 21 | 22 | pipeline :api do 23 | plug :accepts, ["json"] 24 | end 25 | 26 | scope "/", SpotlightWeb do 27 | pipe_through :browser 28 | live "/", PageLive, :index 29 | end 30 | 31 | # Other scopes may use custom stacks. 32 | # scope "/api", SpotlightWeb do 33 | # pipe_through :api 34 | # end 35 | end 36 | -------------------------------------------------------------------------------- /lib/spotlight_web/telemetry.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.Telemetry do 2 | use Supervisor 3 | import Telemetry.Metrics 4 | 5 | def start_link(arg) do 6 | Supervisor.start_link(__MODULE__, arg, name: __MODULE__) 7 | end 8 | 9 | @impl true 10 | def init(_arg) do 11 | children = [ 12 | # Telemetry poller will execute the given period measurements 13 | # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics 14 | {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} 15 | # Add reporters as children of your supervision tree. 16 | # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} 17 | ] 18 | 19 | Supervisor.init(children, strategy: :one_for_one) 20 | end 21 | 22 | def metrics do 23 | [ 24 | # Phoenix Metrics 25 | summary("phoenix.endpoint.stop.duration", 26 | unit: {:native, :millisecond} 27 | ), 28 | summary("phoenix.router_dispatch.stop.duration", 29 | tags: [:route], 30 | unit: {:native, :millisecond} 31 | ), 32 | 33 | # VM Metrics 34 | summary("vm.memory.total", unit: {:byte, :kilobyte}), 35 | summary("vm.total_run_queue_lengths.total"), 36 | summary("vm.total_run_queue_lengths.cpu"), 37 | summary("vm.total_run_queue_lengths.io") 38 | ] 39 | end 40 | 41 | defp periodic_measurements do 42 | [ 43 | # A module, function and arguments to be invoked periodically. 44 | # This function must call :telemetry.execute/3 and a metric must be added above. 45 | # {SpotlightWeb, :count_users, []} 46 | ] 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /lib/spotlight_web/templates/layout/app.html.eex: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | <%= @inner_content %> 5 |
6 | -------------------------------------------------------------------------------- /lib/spotlight_web/templates/layout/live.html.leex: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <%= csrf_meta_tag() %> 6 | <%= live_title_tag assigns[:page_title] || "Spotlight", suffix: " · Phoenix Framework" %> 7 | 8 | 9 | 10 |
11 |
12 | 16 | 17 | 28 |
29 |
30 |
31 | 34 | 35 | 38 | 39 | <%= @inner_content %> 40 |
41 | 42 | 43 | -------------------------------------------------------------------------------- /lib/spotlight_web/templates/layout/root.html.leex: -------------------------------------------------------------------------------- 1 | 2 | 3 | <%= @inner_content %> 4 | 5 | -------------------------------------------------------------------------------- /lib/spotlight_web/views/error_helpers.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.ErrorHelpers do 2 | @moduledoc """ 3 | Conveniences for translating and building error messages. 4 | """ 5 | 6 | use Phoenix.HTML 7 | 8 | @doc """ 9 | Generates tag for inlined form input errors. 10 | """ 11 | def error_tag(form, field) do 12 | Enum.map(Keyword.get_values(form.errors, field), fn error -> 13 | content_tag(:span, translate_error(error), 14 | class: "invalid-feedback", 15 | phx_feedback_for: input_id(form, field) 16 | ) 17 | end) 18 | end 19 | 20 | @doc """ 21 | Translates an error message using gettext. 22 | """ 23 | def translate_error({msg, opts}) do 24 | # When using gettext, we typically pass the strings we want 25 | # to translate as a static argument: 26 | # 27 | # # Translate "is invalid" in the "errors" domain 28 | # dgettext("errors", "is invalid") 29 | # 30 | # # Translate the number of files with plural rules 31 | # dngettext("errors", "1 file", "%{count} files", count) 32 | # 33 | # Because the error messages we show in our forms and APIs 34 | # are defined inside Ecto, we need to translate them dynamically. 35 | # This requires us to call the Gettext module passing our gettext 36 | # backend as first argument. 37 | # 38 | # Note we use the "errors" domain, which means translations 39 | # should be written to the errors.po file. The :count option is 40 | # set by Ecto and indicates we should also apply plural rules. 41 | if count = opts[:count] do 42 | Gettext.dngettext(SpotlightWeb.Gettext, "errors", msg, msg, count, opts) 43 | else 44 | Gettext.dgettext(SpotlightWeb.Gettext, "errors", msg, opts) 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /lib/spotlight_web/views/error_view.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.ErrorView do 2 | use SpotlightWeb, :view 3 | 4 | # If you want to customize a particular status code 5 | # for a certain format, you may uncomment below. 6 | # def render("500.html", _assigns) do 7 | # "Internal Server Error" 8 | # end 9 | 10 | # By default, Phoenix returns the status message from 11 | # the template name. For example, "404.html" becomes 12 | # "Not Found". 13 | def template_not_found(template, _assigns) do 14 | Phoenix.Controller.status_message_from_template(template) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /lib/spotlight_web/views/layout_view.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.LayoutView do 2 | use SpotlightWeb, :view 3 | @app_js_path Path.join(__DIR__, "../../../priv/static/js/app.js") 4 | @app_css_path Path.join(__DIR__, "../../../priv/static/css/app.css") 5 | 6 | if Mix.env() == :dev do 7 | def render("app.js", _), do: File.read!(@app_js_path) 8 | def render("app.css", _), do: File.read!(@app_css_path) 9 | else 10 | @app_js File.read!(@app_js_path) 11 | @app_css File.read!(@app_css_path) 12 | 13 | def render("app.js", _), do: @app_js 14 | def render("app.css", _), do: @app_css 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Spotlight.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :spotlight, 7 | name: "Spotlight", 8 | package: package(), 9 | version: "0.1.0", 10 | elixir: "~> 1.7", 11 | elixirc_paths: elixirc_paths(Mix.env()), 12 | compilers: [:phoenix, :gettext] ++ Mix.compilers(), 13 | start_permanent: Mix.env() == :prod, 14 | aliases: aliases(), 15 | deps: deps() 16 | ] 17 | end 18 | 19 | # Configuration for the OTP application. 20 | # 21 | # Type `mix help compile.app` for more information. 22 | def application do 23 | [ 24 | mod: {Spotlight.Application, []}, 25 | extra_applications: [:logger, :runtime_tools] 26 | ] 27 | end 28 | 29 | # Specifies which paths to compile per environment. 30 | defp elixirc_paths(:test), do: ["lib", "test/support"] 31 | defp elixirc_paths(_), do: ["lib"] 32 | 33 | # Specifies your project dependencies. 34 | # 35 | # Type `mix help deps` for examples and options. 36 | defp deps do 37 | [ 38 | {:phoenix, "~> 1.5.4"}, 39 | {:phoenix_live_view, "~> 0.14.0"}, 40 | {:floki, ">= 0.0.0", only: :test}, 41 | {:phoenix_html, "~> 2.11"}, 42 | {:phoenix_live_reload, "~> 1.2", only: :dev}, 43 | {:telemetry_metrics, "~> 0.4"}, 44 | {:telemetry_poller, "~> 0.4"}, 45 | {:gettext, "~> 0.11"}, 46 | {:jason, "~> 1.0"}, 47 | {:plug_cowboy, "~> 2.0"}, 48 | {:dog_sketch, "~> 0.1.2"}, 49 | {:ex_doc, "~> 0.22.2", only: :dev, runtime: false} 50 | ] 51 | end 52 | 53 | defp package do 54 | [ 55 | description: "Low-overhead Phoenix Performance Graphs", 56 | licenses: ["MIT"], 57 | links: %{}, 58 | maintainers: ["Derek Kraan", "Sanne Kalkman", "Will Rogers"] 59 | ] 60 | end 61 | 62 | # Aliases are shortcuts or tasks specific to the current project. 63 | # For example, to install project dependencies and perform other setup tasks, run: 64 | # 65 | # $ mix setup 66 | # 67 | # See the documentation for `Mix` for more info on aliases. 68 | defp aliases do 69 | [ 70 | setup: ["deps.get", "cmd npm install --prefix assets"] 71 | ] 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "cowboy": {:hex, :cowboy, "2.8.0", "f3dc62e35797ecd9ac1b50db74611193c29815401e53bac9a5c0577bd7bc667d", [:rebar3], [{:cowlib, "~> 2.9.1", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "~> 1.7.1", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "4643e4fba74ac96d4d152c75803de6fad0b3fa5df354c71afdd6cbeeb15fac8a"}, 3 | "cowlib": {:hex, :cowlib, "2.9.1", "61a6c7c50cf07fdd24b2f45b89500bb93b6686579b069a89f88cb211e1125c78", [:rebar3], [], "hexpm", "e4175dc240a70d996156160891e1c62238ede1729e45740bdd38064dad476170"}, 4 | "dog_sketch": {:hex, :dog_sketch, "0.1.2", "10c51b4d404e351309d74f9bce29a5a8cfbf12c309a90801fcfa0088ef116164", [:mix], [], "hexpm", "d6c6102a7434a8f49e4368eb3ba01c8eaf1ea455463fb4f74735844a51d9a0d8"}, 5 | "earmark_parser": {:hex, :earmark_parser, "1.4.10", "6603d7a603b9c18d3d20db69921527f82ef09990885ed7525003c7fe7dc86c56", [:mix], [], "hexpm", "8e2d5370b732385db2c9b22215c3f59c84ac7dda7ed7e544d7c459496ae519c0"}, 6 | "ex_doc": {:hex, :ex_doc, "0.22.5", "d2312c99f52cb1f98371e28f68259b4e0cee13d0122baedaf74a8e44e299a35b", [:mix], [{:earmark_parser, "~> 1.4.0", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "d6ac685fd0b226805db96f7fbb384cbf8e01903ddb902ff66c9b189104705cae"}, 7 | "file_system": {:hex, :file_system, "0.2.8", "f632bd287927a1eed2b718f22af727c5aeaccc9a98d8c2bd7bff709e851dc986", [:mix], [], "hexpm", "97a3b6f8d63ef53bd0113070102db2ce05352ecf0d25390eb8d747c2bde98bca"}, 8 | "floki": {:hex, :floki, "0.28.0", "0d0795a17189510ee01323e6990f906309e9fc6e8570219135211f1264d78c7f", [:mix], [{:html_entities, "~> 0.5.0", [hex: :html_entities, repo: "hexpm", optional: false]}], "hexpm", "db1549560874ebba5a6367e46c3aec5fedd41f2757ad6efe567efb04b4d4ee55"}, 9 | "gettext": {:hex, :gettext, "0.18.1", "89e8499b051c7671fa60782faf24409b5d2306aa71feb43d79648a8bc63d0522", [:mix], [], "hexpm", "e70750c10a5f88cb8dc026fc28fa101529835026dec4a06dba3b614f2a99c7a9"}, 10 | "html_entities": {:hex, :html_entities, "0.5.1", "1c9715058b42c35a2ab65edc5b36d0ea66dd083767bef6e3edb57870ef556549", [:mix], [], "hexpm", "30efab070904eb897ff05cd52fa61c1025d7f8ef3a9ca250bc4e6513d16c32de"}, 11 | "jason": {:hex, :jason, "1.2.2", "ba43e3f2709fd1aa1dce90aaabfd039d000469c05c56f0b8e31978e03fa39052", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "18a228f5f0058ee183f29f9eae0805c6e59d61c3b006760668d8d18ff0d12179"}, 12 | "makeup": {:hex, :makeup, "1.0.3", "e339e2f766d12e7260e6672dd4047405963c5ec99661abdc432e6ec67d29ef95", [:mix], [{:nimble_parsec, "~> 0.5", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "2e9b4996d11832947731f7608fed7ad2f9443011b3b479ae288011265cdd3dad"}, 13 | "makeup_elixir": {:hex, :makeup_elixir, "0.14.1", "4f0e96847c63c17841d42c08107405a005a2680eb9c7ccadfd757bd31dabccfb", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "f2438b1a80eaec9ede832b5c41cd4f373b38fd7aa33e3b22d9db79e640cbde11"}, 14 | "mime": {:hex, :mime, "1.4.0", "5066f14944b470286146047d2f73518cf5cca82f8e4815cf35d196b58cf07c47", [:mix], [], "hexpm", "75fa42c4228ea9a23f70f123c74ba7cece6a03b1fd474fe13f6a7a85c6ea4ff6"}, 15 | "nimble_parsec": {:hex, :nimble_parsec, "0.6.0", "32111b3bf39137144abd7ba1cce0914533b2d16ef35e8abc5ec8be6122944263", [:mix], [], "hexpm", "27eac315a94909d4dc68bc07a4a83e06c8379237c5ea528a9acff4ca1c873c52"}, 16 | "phoenix": {:hex, :phoenix, "1.5.4", "0fca9ce7e960f9498d6315e41fcd0c80bfa6fbeb5fa3255b830c67fdfb7e703f", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_html, "~> 2.13", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 1.0 or ~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.1.2 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4e516d131fde87b568abd62e1b14aa07ba7d5edfd230bab4e25cc9dedbb39135"}, 17 | "phoenix_html": {:hex, :phoenix_html, "2.14.2", "b8a3899a72050f3f48a36430da507dd99caf0ac2d06c77529b1646964f3d563e", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "58061c8dfd25da5df1ea0ca47c972f161beb6c875cd293917045b92ffe1bf617"}, 18 | "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.2.4", "940c0344b1d66a2e46eef02af3a70e0c5bb45a4db0bf47917add271b76cd3914", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "38f9308357dea4cc77f247e216da99fcb0224e05ada1469167520bed4cb8cccd"}, 19 | "phoenix_live_view": {:hex, :phoenix_live_view, "0.14.4", "7286a96287cd29b594ce4a7314249cea7311af04a06c0fa3e50932e188e73996", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.5.3", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 0.5", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc4f8cf205c784eeccee35de8afbfeb995ce5511ac4839db63d6d67a5ba091d1"}, 20 | "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.0.0", "a1ae76717bb168cdeb10ec9d92d1480fec99e3080f011402c0a2d68d47395ffb", [:mix], [], "hexpm", "c52d948c4f261577b9c6fa804be91884b381a7f8f18450c5045975435350f771"}, 21 | "plug": {:hex, :plug, "1.10.4", "41eba7d1a2d671faaf531fa867645bd5a3dce0957d8e2a3f398ccff7d2ef017f", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "ad1e233fe73d2eec56616568d260777b67f53148a999dc2d048f4eb9778fe4a0"}, 22 | "plug_cowboy": {:hex, :plug_cowboy, "2.3.0", "149a50e05cb73c12aad6506a371cd75750c0b19a32f81866e1a323dda9e0e99d", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "bc595a1870cef13f9c1e03df56d96804db7f702175e4ccacdb8fc75c02a7b97e"}, 23 | "plug_crypto": {:hex, :plug_crypto, "1.1.2", "bdd187572cc26dbd95b87136290425f2b580a116d3fb1f564216918c9730d227", [:mix], [], "hexpm", "6b8b608f895b6ffcfad49c37c7883e8df98ae19c6a28113b02aa1e9c5b22d6b5"}, 24 | "ranch": {:hex, :ranch, "1.7.1", "6b1fab51b49196860b733a49c07604465a47bdb78aa10c1c16a3d199f7f8c881", [:rebar3], [], "hexpm", "451d8527787df716d99dc36162fca05934915db0b6141bbdac2ea8d3c7afc7d7"}, 25 | "telemetry": {:hex, :telemetry, "0.4.2", "2808c992455e08d6177322f14d3bdb6b625fbcfd233a73505870d8738a2f4599", [:rebar3], [], "hexpm", "2d1419bd9dda6a206d7b5852179511722e2b18812310d304620c7bd92a13fcef"}, 26 | "telemetry_metrics": {:hex, :telemetry_metrics, "0.5.0", "1b796e74add83abf844e808564275dfb342bcc930b04c7577ab780e262b0d998", [:mix], [{:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "31225e6ce7a37a421a0a96ec55244386aec1c190b22578bd245188a4a33298fd"}, 27 | "telemetry_poller": {:hex, :telemetry_poller, "0.5.1", "21071cc2e536810bac5628b935521ff3e28f0303e770951158c73eaaa01e962a", [:rebar3], [{:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4cab72069210bc6e7a080cec9afffad1b33370149ed5d379b81c7c5f0c663fd4"}, 28 | } 29 | -------------------------------------------------------------------------------- /priv/gettext/en/LC_MESSAGES/errors.po: -------------------------------------------------------------------------------- 1 | ## `msgid`s in this file come from POT (.pot) files. 2 | ## 3 | ## Do not add, change, or remove `msgid`s manually here as 4 | ## they're tied to the ones in the corresponding POT file 5 | ## (with the same domain). 6 | ## 7 | ## Use `mix gettext.extract --merge` or `mix gettext.merge` 8 | ## to merge POT files into PO files. 9 | msgid "" 10 | msgstr "" 11 | "Language: en\n" 12 | -------------------------------------------------------------------------------- /priv/gettext/errors.pot: -------------------------------------------------------------------------------- 1 | ## This is a PO Template file. 2 | ## 3 | ## `msgid`s here are often extracted from source code. 4 | ## Add new translations manually only if they're dynamic 5 | ## translations that can't be statically extracted. 6 | ## 7 | ## Run `mix gettext.extract` to bring this file up to 8 | ## date. Leave `msgstr`s empty as changing them here has no 9 | ## effect: edit them in PO (`.po`) files instead. 10 | 11 | -------------------------------------------------------------------------------- /test/spotlight_web/live/page_live_test.exs: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.PageLiveTest do 2 | use SpotlightWeb.ConnCase 3 | 4 | import Phoenix.LiveViewTest 5 | 6 | test "disconnected and connected render", %{conn: conn} do 7 | {:ok, page_live, disconnected_html} = live(conn, "/") 8 | assert disconnected_html =~ "Welcome to Phoenix!" 9 | assert render(page_live) =~ "Welcome to Phoenix!" 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /test/spotlight_web/views/error_view_test.exs: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.ErrorViewTest do 2 | use SpotlightWeb.ConnCase, async: true 3 | 4 | # Bring render/3 and render_to_string/3 for testing custom views 5 | import Phoenix.View 6 | 7 | test "renders 404.html" do 8 | assert render_to_string(SpotlightWeb.ErrorView, "404.html", []) == "Not Found" 9 | end 10 | 11 | test "renders 500.html" do 12 | assert render_to_string(SpotlightWeb.ErrorView, "500.html", []) == "Internal Server Error" 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /test/spotlight_web/views/layout_view_test.exs: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.LayoutViewTest do 2 | use SpotlightWeb.ConnCase, async: true 3 | 4 | # When testing helpers, you may want to import Phoenix.HTML and 5 | # use functions such as safe_to_string() to convert the helper 6 | # result into an HTML string. 7 | # import Phoenix.HTML 8 | end 9 | -------------------------------------------------------------------------------- /test/support/channel_case.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.ChannelCase do 2 | @moduledoc """ 3 | This module defines the test case to be used by 4 | channel tests. 5 | 6 | Such tests rely on `Phoenix.ChannelTest` and also 7 | import other functionality to make it easier 8 | to build common data structures and query the data layer. 9 | 10 | Finally, if the test case interacts with the database, 11 | we enable the SQL sandbox, so changes done to the database 12 | are reverted at the end of every test. If you are using 13 | PostgreSQL, you can even run database tests asynchronously 14 | by setting `use SpotlightWeb.ChannelCase, async: true`, although 15 | this option is not recommended for other databases. 16 | """ 17 | 18 | use ExUnit.CaseTemplate 19 | 20 | using do 21 | quote do 22 | # Import conveniences for testing with channels 23 | import Phoenix.ChannelTest 24 | import SpotlightWeb.ChannelCase 25 | 26 | # The default endpoint for testing 27 | @endpoint SpotlightWeb.Endpoint 28 | end 29 | end 30 | 31 | setup _tags do 32 | :ok 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /test/support/conn_case.ex: -------------------------------------------------------------------------------- 1 | defmodule SpotlightWeb.ConnCase do 2 | @moduledoc """ 3 | This module defines the test case to be used by 4 | tests that require setting up a connection. 5 | 6 | Such tests rely on `Phoenix.ConnTest` and also 7 | import other functionality to make it easier 8 | to build common data structures and query the data layer. 9 | 10 | Finally, if the test case interacts with the database, 11 | we enable the SQL sandbox, so changes done to the database 12 | are reverted at the end of every test. If you are using 13 | PostgreSQL, you can even run database tests asynchronously 14 | by setting `use SpotlightWeb.ConnCase, async: true`, although 15 | this option is not recommended for other databases. 16 | """ 17 | 18 | use ExUnit.CaseTemplate 19 | 20 | using do 21 | quote do 22 | # Import conveniences for testing with connections 23 | import Plug.Conn 24 | import Phoenix.ConnTest 25 | import SpotlightWeb.ConnCase 26 | 27 | alias SpotlightWeb.Router.Helpers, as: Routes 28 | 29 | # The default endpoint for testing 30 | @endpoint SpotlightWeb.Endpoint 31 | end 32 | end 33 | 34 | setup _tags do 35 | {:ok, conn: Phoenix.ConnTest.build_conn()} 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------