├── .dockerignore ├── .formatter.exs ├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── assets ├── .babelrc ├── css │ ├── app.scss │ └── phoenix.css ├── js │ └── app.js ├── package-lock.json ├── package.json ├── static │ ├── favicon.ico │ ├── images │ │ └── phoenix.png │ └── robots.txt └── webpack.config.js ├── config ├── config.exs ├── dev.exs ├── prod.exs ├── releases.exs └── test.exs ├── coveralls.json ├── elixir_buildpack.config ├── entrypoint.sh ├── fly.toml ├── lib ├── live_view_counter.ex ├── live_view_counter │ ├── application.ex │ ├── count.ex │ └── presence.ex ├── live_view_counter_web.ex └── live_view_counter_web │ ├── channels │ └── user_socket.ex │ ├── endpoint.ex │ ├── gettext.ex │ ├── live │ ├── counter.ex │ ├── page_live.ex │ └── page_live.html.leex │ ├── router.ex │ ├── telemetry.ex │ ├── templates │ ├── counter.html.leex │ └── layout │ │ ├── app.html.eex │ │ ├── live.html.leex │ │ └── root.html.leex │ └── views │ ├── error_helpers.ex │ ├── error_view.ex │ └── layout_view.ex ├── mix.exs ├── mix.lock ├── phoenix_static_buildpack.config ├── priv └── gettext │ ├── en │ └── LC_MESSAGES │ │ └── errors.po │ └── errors.pot └── test ├── live_view_counter_web ├── live │ ├── counter_test.exs │ └── page_live_test.exs └── views │ ├── error_view_test.exs │ └── layout_view_test.exs ├── support ├── channel_case.ex └── conn_case.ex └── test_helper.exs /.dockerignore: -------------------------------------------------------------------------------- 1 | assets/node_modules 2 | _build -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | [ 2 | import_deps: [:phoenix], 3 | inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /cover 3 | /deps 4 | /doc 5 | /.fetch 6 | erl_crash.dump 7 | *.ez 8 | *.beam 9 | /config/*.secret.exs 10 | 11 | # Ignore package tarball (built via "mix hex.build"). 12 | live_view_counter-*.tar 13 | 14 | # If NPM crashes, it generates a log, let's ignore it too. 15 | npm-debug.log 16 | 17 | # Generated by asdf 18 | .tool-versions 19 | 20 | # The directory NPM downloads your dependencies sources to. 21 | /assets/node_modules/ 22 | 23 | # Since we are building assets from assets/, 24 | # we ignore priv/static. You may want to comment 25 | # this depending on your deployment strategy. 26 | /priv/static/ 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: elixir 2 | elixir: 3 | - 1.10.1 4 | otp_release: 5 | - 22.0 6 | env: 7 | - MIX_ENV=test 8 | script: 9 | - mix deps.get 10 | - mix compile 11 | - mix coveralls.json 12 | after_success: 13 | - bash <(curl -s https://codecov.io/bash) 14 | # cache: 15 | # directories: 16 | # - _build 17 | # - deps 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM elixir:1.10-alpine AS build 2 | 3 | # install build dependencies 4 | RUN apk add --no-cache build-base npm 5 | 6 | # prepare build dir 7 | WORKDIR /app 8 | 9 | # install hex + rebar 10 | RUN mix local.hex --force && \ 11 | mix local.rebar --force 12 | 13 | # set build ENV 14 | ENV SECRET_KEY_BASE=nokey 15 | 16 | # install mix dependencies 17 | COPY mix.exs mix.lock ./ 18 | COPY config config 19 | RUN mix deps.get --only prod 20 | RUN MIX_ENV=prod mix deps.compile 21 | 22 | # build assets 23 | COPY assets/package.json assets/package-lock.json ./assets/ 24 | RUN npm --prefix ./assets ci --progress=false --no-audit --loglevel=error 25 | 26 | COPY priv priv 27 | COPY assets assets 28 | RUN npm run --prefix ./assets deploy 29 | RUN MIX_ENV=prod mix phx.digest 30 | 31 | # compile and build release 32 | COPY lib lib 33 | # uncomment COPY if rel/ exists 34 | # COPY rel rel 35 | RUN MIX_ENV=prod mix release 36 | 37 | # prepare release image 38 | FROM alpine:3.9 AS app 39 | RUN apk add --no-cache openssl ncurses-libs 40 | 41 | WORKDIR /app 42 | 43 | RUN chown nobody:nobody /app 44 | 45 | USER nobody:nobody 46 | 47 | COPY --from=build --chown=nobody:nobody /app/_build/prod/rel/live_view_counter ./ 48 | 49 | ADD entrypoint.sh ./ 50 | 51 | ENV HOME=/app 52 | ENV MIX_ENV=prod 53 | ENV SECRET_KEY_BASE=nokey 54 | ENV PORT=4000 55 | ENTRYPOINT ["/app/entrypoint.sh"] 56 | CMD ["bin/live_view_counter", "start"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fly.io Elixir Hiring Project 2 | 3 | Hello! This is a hiring project for our [Elixir dev advocate](https://fly.io/blog/we-are-hiring-elixir-developer-advocates/) position. If you apply, we'll ask you to do this project so we can assess your ability to work with Elixir/Phoenix/LiveView. This is a pretty good representation of the type of work we need to do at Fly.io. 4 | 5 | ## The purpose 6 | 7 | This is a Phoenix/LiveView app that demonstrates LiveView "multiplayer" by letting people collaboratively increment/decrement a counter. We modified [`dwyl/phoenix-liveview-counter-tutorial`](https://github.com/dwyl/phoenix-liveview-counter-tutorial) to add clustering and a click breakdown by region. 8 | 9 | You can see it in action here: https://liveview-counter.fly.dev/ 10 | 11 | If you work as an Elixir dev advocate at Fly.io, this is the type of project we'll want you to produce. It shows how to use LiveView and, because we want to do well as a company, why Fly.io is a good place to deploy a LiveView project. 12 | 13 | We'll also want you to blog about it. You can think of the job as "come up with good examples on Fly" and "write about them". 14 | 15 | ## Hiring project 16 | 17 | For hiring purposes, we don't (yet) want you to do a from-scratch project like this. We do want to see that you can work with Elixir, Phoenix, and distributed apps. So we'd like you to improve this project. 18 | 19 | When you load liveview-counter.fly.dev, you'll notice there are only one or two regions showing in the output. This is a flaw, it happens because we're using pubsub, each app instance keeps its own count, and these only get communicated when someone clicks and triggers a publish. 20 | 21 | Instead, we'd like the demo to do what users would expect at load time. It should show numbers for every region the first time someone visits. 22 | 23 | When you run the app locally, you can set a `FLY_REGION` environment variable to "fake" a region. Try `ord` or `sin` or `syd` or `hkg` or `fra`, for example. 24 | 25 | You'll need to run two instances of the app _and_ cluster them locally to test your changes. `libcluster` is relatively simple to work with, you might use the [`Epmd`](https://hexdocs.pm/libcluster/Cluster.Strategy.Epmd.html#content) strategy in development mode to cluster two test processes. 26 | 27 | We expect this to take about two hours for experience Elixir/Phoenix devs, but you can spend as much time on it as you want if you're still learning. 28 | 29 | ## Submit your work 30 | 31 | 1. Clone this repository locally 32 | 2. Create a branch for your changes 33 | 3. Do some development 34 | 4. When you're ready, create a patchset to submit 35 | * `git diff main > fly-work-sample.patch.txt` 36 | 5. Email the patch to jobs+elixir@fly.io (or reply to your existing email chain) 37 | 38 | ## Evaluation process 39 | 40 | Once we receive your patch, we will anonymize it and have three Fly.io engineers evaluate it. This takes 3-5 days and we will let you know as soon as we have results. 41 | 42 | ## What we care about 43 | 44 | We have two specific things we're looking for: 45 | 46 | * Does it show clicks/presence from every region at first load? 47 | * Is clustering in dev mode configured? 48 | 49 | Don't waste time on: 50 | 51 | * Deploying the app, running it locally is just fine 52 | * Updating the README or writing docs 53 | * Writing tests 54 | * Design / refactoring / other cleanup -------------------------------------------------------------------------------- /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 | 5 | /* */ 6 | 7 | th.region{ 8 | img{ 9 | width: 40px; 10 | height: 40px; 11 | vertical-align: middle; 12 | border: 1px solid black; 13 | border-radius: 50%; 14 | } 15 | } 16 | .icon { 17 | width: 40px; 18 | height: 40px; 19 | vertical-align: middle; 20 | margin-left: -20px; 21 | } 22 | 23 | /* LiveView specific classes for your customizations */ 24 | .invalid-feedback { 25 | color: #a94442; 26 | display: block; 27 | margin: -1rem 0 2rem; 28 | } 29 | 30 | .phx-no-feedback.invalid-feedback, .phx-no-feedback .invalid-feedback { 31 | display: none; 32 | } 33 | 34 | .phx-click-loading { 35 | opacity: 0.5; 36 | transition: opacity 1s ease-out; 37 | } 38 | 39 | .phx-disconnected{ 40 | cursor: wait; 41 | } 42 | .phx-disconnected *{ 43 | pointer-events: none; 44 | } 45 | 46 | .phx-modal { 47 | opacity: 1!important; 48 | position: fixed; 49 | z-index: 1; 50 | left: 0; 51 | top: 0; 52 | width: 100%; 53 | height: 100%; 54 | overflow: auto; 55 | background-color: rgb(0,0,0); 56 | background-color: rgba(0,0,0,0.4); 57 | } 58 | 59 | .phx-modal-content { 60 | background-color: #fefefe; 61 | margin: 15% auto; 62 | padding: 20px; 63 | border: 1px solid #888; 64 | width: 80%; 65 | } 66 | 67 | .phx-modal-close { 68 | color: #aaa; 69 | float: right; 70 | font-size: 28px; 71 | font-weight: bold; 72 | } 73 | 74 | .phx-modal-close:hover, 75 | .phx-modal-close:focus { 76 | color: black; 77 | text-decoration: none; 78 | cursor: pointer; 79 | } 80 | 81 | 82 | /* Alerts and form errors */ 83 | .alert { 84 | padding: 15px; 85 | margin-bottom: 20px; 86 | border: 1px solid transparent; 87 | border-radius: 4px; 88 | } 89 | .alert-info { 90 | color: #31708f; 91 | background-color: #d9edf7; 92 | border-color: #bce8f1; 93 | } 94 | .alert-warning { 95 | color: #8a6d3b; 96 | background-color: #fcf8e3; 97 | border-color: #faebcc; 98 | } 99 | .alert-danger { 100 | color: #a94442; 101 | background-color: #f2dede; 102 | border-color: #ebccd1; 103 | } 104 | .alert p { 105 | margin-bottom: 0; 106 | } 107 | .alert:empty { 108 | display: none; 109 | } 110 | -------------------------------------------------------------------------------- /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: 80.0rem; 23 | padding: 0 2.0rem; 24 | position: relative; 25 | width: 100% 26 | } 27 | select { 28 | width: auto; 29 | } 30 | 31 | /* Phoenix promo and logo */ 32 | .phx-hero { 33 | text-align: center; 34 | border-bottom: 1px solid #e3e3e3; 35 | background: #eee; 36 | border-radius: 6px; 37 | padding: 3em 3em 1em; 38 | margin-bottom: 3rem; 39 | font-weight: 200; 40 | font-size: 120%; 41 | } 42 | .phx-hero input { 43 | background: #ffffff; 44 | } 45 | .phx-logo { 46 | min-width: 300px; 47 | margin: 1rem; 48 | display: block; 49 | } 50 | .phx-logo img { 51 | width: auto; 52 | display: block; 53 | } 54 | 55 | /* Headers */ 56 | header { 57 | width: 100%; 58 | background: #fdfdfd; 59 | border-bottom: 1px solid #eaeaea; 60 | margin-bottom: 2rem; 61 | } 62 | header section { 63 | align-items: center; 64 | display: flex; 65 | flex-direction: column; 66 | justify-content: space-between; 67 | } 68 | header section :first-child { 69 | order: 2; 70 | } 71 | header section :last-child { 72 | order: 1; 73 | } 74 | header nav ul, 75 | header nav li { 76 | margin: 0; 77 | padding: 0; 78 | display: block; 79 | text-align: right; 80 | white-space: nowrap; 81 | } 82 | header nav ul { 83 | margin: 1rem; 84 | margin-top: 0; 85 | } 86 | header nav a { 87 | display: block; 88 | } 89 | 90 | @media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ 91 | header section { 92 | flex-direction: row; 93 | } 94 | header nav ul { 95 | margin: 1rem; 96 | } 97 | .phx-logo { 98 | flex-basis: 527px; 99 | margin: 2rem 1rem; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /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 | 20 | let Hooks = {} 21 | Hooks.RTT = { 22 | mounted(){ 23 | this.timer = setInterval(() => { 24 | let beforeTime = (new Date().getTime()) 25 | this.pushEvent("ping", {}, resp => { 26 | let rtt = (new Date().getTime()) - beforeTime 27 | this.el.innerText = `${rtt}ms` 28 | }) 29 | }, 1000) 30 | }, 31 | destroyed(){ clearInterval(this.timer) } 32 | } 33 | let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") 34 | let liveSocket = new LiveSocket("/live", Socket, { 35 | hooks: Hooks, 36 | params: {_csrf_token: csrfToken}, 37 | }); 38 | 39 | // Show progress bar on live navigation and form submits 40 | window.addEventListener("phx:page-loading-start", info => NProgress.start()) 41 | window.addEventListener("phx:page-loading-stop", info => NProgress.done()) 42 | 43 | // connect if there are any LiveViews on the page 44 | liveSocket.connect() 45 | 46 | // expose liveSocket on window for web console debug logs and latency simulation: 47 | // >> liveSocket.enableDebug() 48 | // >> liveSocket.enableLatencySim(1000) 49 | window.liveSocket = liveSocket -------------------------------------------------------------------------------- /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 | "phoenix": "file:../deps/phoenix", 11 | "phoenix_html": "file:../deps/phoenix_html", 12 | "phoenix_live_view": "file:../deps/phoenix_live_view", 13 | "nprogress": "^0.2.0" 14 | }, 15 | "devDependencies": { 16 | "@babel/core": "^7.0.0", 17 | "@babel/preset-env": "^7.0.0", 18 | "babel-loader": "^8.0.0", 19 | "copy-webpack-plugin": "^5.1.1", 20 | "css-loader": "^3.4.2", 21 | "sass-loader": "^8.0.2", 22 | "node-sass": "^4.13.1", 23 | "hard-source-webpack-plugin": "^0.13.1", 24 | "mini-css-extract-plugin": "^0.9.0", 25 | "optimize-css-assets-webpack-plugin": "^5.0.1", 26 | "terser-webpack-plugin": "^2.3.2", 27 | "webpack": "4.41.5", 28 | "webpack-cli": "^3.3.2" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /assets/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/superfly/elixir-hiring-project/ae63ddd2d02161cfb3040e9d89351d5a7cce413b/assets/static/favicon.ico -------------------------------------------------------------------------------- /assets/static/images/phoenix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/superfly/elixir-hiring-project/ae63ddd2d02161cfb3040e9d89351d5a7cce413b/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: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"], 40 | }, 41 | ], 42 | }, 43 | plugins: [ 44 | new MiniCssExtractPlugin({ filename: "../css/app.css" }), 45 | new CopyWebpackPlugin([{ from: "static/", to: "../" }]), 46 | ].concat(devMode ? [new HardSourceWebpackPlugin()] : []), 47 | }; 48 | }; 49 | -------------------------------------------------------------------------------- /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 :live_view_counter, LiveViewCounterWeb.Endpoint, 12 | url: [host: "localhost"], 13 | secret_key_base: "s0e+LZ/leTtv3peHaFhnd2rbncAeV5qlR1rNShKXDMSRbVgU2Aar8nyXszsQrZ1p", 14 | render_errors: [view: LiveViewCounterWeb.ErrorView, accepts: ~w(html json), layout: false], 15 | pubsub_server: LiveViewCounter.PubSub, 16 | live_view: [signing_salt: "iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c"] 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 :live_view_counter, LiveViewCounterWeb.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 :live_view_counter, LiveViewCounterWeb.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/live_view_counter_web/(live|views)/.*(ex)$", 55 | ~r"lib/live_view_counter_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 :live_view_counter, LiveViewCounterWeb.Endpoint, 13 | load_from_system_env: true, 14 | http: [port: {:system, "PORT"}], 15 | url: [scheme: "https", host: "liveview-counter.fly.dev", port: 443], 16 | force_ssl: [rewrite_on: [:x_forwarded_proto]], 17 | cache_static_manifest: "priv/static/cache_manifest.json", 18 | secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE") 19 | 20 | 21 | # Do not print debug messages in production 22 | config :logger, level: :info 23 | -------------------------------------------------------------------------------- /config/releases.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | secret_key_base = 4 | System.get_env("SECRET_KEY_BASE") || 5 | raise """ 6 | environment variable SECRET_KEY_BASE is missing. 7 | You can generate one by calling: mix phx.gen.secret 8 | """ 9 | 10 | app_name = 11 | System.get_env("FLY_APP_NAME") || 12 | raise "FLY_APP_NAME not available" 13 | 14 | config :live_view_counter, LiveViewCounterWeb.Endpoint, 15 | server: true, 16 | http: [ 17 | port: String.to_integer(System.get_env("PORT") || "4000"), 18 | transport_options: [socket_opts: [:inet6]] 19 | ], 20 | secret_key_base: secret_key_base 21 | 22 | 23 | config :libcluster, 24 | debug: true, 25 | topologies: [ 26 | fly6pn: [ 27 | strategy: Elixir.Cluster.Strategy.DNSPoll, 28 | config: [ 29 | polling_interval: 5_000, 30 | query: "#{app_name}.internal", 31 | node_basename: app_name]]] 32 | 33 | # Do not include metadata nor timestamps in development logs 34 | config :logger, :console, format: "[$level] $message\n" 35 | -------------------------------------------------------------------------------- /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 :live_view_counter, LiveViewCounterWeb.Endpoint, 6 | http: [port: 4002], 7 | server: false 8 | 9 | # Print only warnings and errors during test 10 | config :logger, level: :warn 11 | -------------------------------------------------------------------------------- /coveralls.json: -------------------------------------------------------------------------------- 1 | { 2 | "coverage_options": { 3 | "minimum_coverage": 100 4 | }, 5 | "skip_files": [ 6 | "lib/live_view_counter/application.ex", 7 | "lib/live_view_counter_web.ex", 8 | "lib/live_view_counter_web/views/error_helpers.ex", 9 | "lib/live_view_counter_web/router.ex", 10 | "lib/live_view_counter_web/live/page_live.ex", 11 | "test/" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /elixir_buildpack.config: -------------------------------------------------------------------------------- 1 | # Elixir version 2 | elixir_version=1.10.4 3 | 4 | # Erlang version 5 | # available versions https://github.com/HashNuke/heroku-buildpack-elixir-otp-builds/blob/master/otp-versions 6 | erlang_version=23.0.3 7 | 8 | # always_rebuild=true -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ip=$(grep fly-local-6pn /etc/hosts | cut -f 1) 4 | export RELEASE_DISTRIBUTION=name 5 | export RELEASE_NODE=$FLY_APP_NAME@$ip 6 | export ELIXIR_ERL_OPTIONS="-proto_dist inet6_tcp" 7 | exec $@ -------------------------------------------------------------------------------- /fly.toml: -------------------------------------------------------------------------------- 1 | # fly.toml file generated for liveview-counter on 2021-02-18T14:28:52-06:00 2 | 3 | app = "liveview-counter" 4 | 5 | kill_signal = "SIGTERM" 6 | kill_timeout = 5 7 | 8 | [experimental] 9 | private_network = true 10 | 11 | [[services]] 12 | internal_port = 4000 13 | protocol = "tcp" 14 | 15 | [services.concurrency] 16 | hard_limit = 25 17 | soft_limit = 20 18 | 19 | [[services.ports]] 20 | handlers = ["http"] 21 | port = "80" 22 | 23 | [[services.ports]] 24 | handlers = ["tls", "http"] 25 | port = "443" 26 | 27 | [[services.tcp_checks]] 28 | grace_period = "30s" # seems to take about 30s to boot 29 | interval = "10s" 30 | port = "8080" 31 | restart_limit = 0 32 | timeout = "2s" 33 | -------------------------------------------------------------------------------- /lib/live_view_counter.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounter do 2 | @moduledoc """ 3 | LiveViewCounter 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/live_view_counter/application.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounter.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 | topologies = Application.get_env(:libcluster, :topologies) || [] 10 | children = [ 11 | # start libcluster 12 | {Cluster.Supervisor, [topologies, [name: LiveViewCounter.ClusterSupervisor]]}, 13 | # Start the App State 14 | LiveViewCounter.Count, 15 | # Start the Telemetry supervisor 16 | LiveViewCounterWeb.Telemetry, 17 | # Start the PubSub system 18 | {Phoenix.PubSub, name: LiveViewCounter.PubSub}, 19 | LiveViewCounter.Presence, 20 | # Start the Endpoint (http/https) 21 | LiveViewCounterWeb.Endpoint 22 | # Start a worker by calling: LiveViewCounter.Worker.start_link(arg) 23 | # {LiveViewCounter.Worker, arg} 24 | ] 25 | 26 | # See https://hexdocs.pm/elixir/Supervisor.html 27 | # for other strategies and supported options 28 | opts = [strategy: :one_for_one, name: LiveViewCounter.Supervisor] 29 | Supervisor.start_link(children, opts) 30 | end 31 | 32 | # Tell Phoenix to update the endpoint configuration 33 | # whenever the application is updated. 34 | def config_change(changed, _new, removed) do 35 | LiveViewCounterWeb.Endpoint.config_change(changed, removed) 36 | :ok 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /lib/live_view_counter/count.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounter.Count do 2 | use GenServer 3 | 4 | alias Phoenix.PubSub 5 | 6 | @name :count_server 7 | 8 | @start_value 0 9 | 10 | def fly_region do 11 | System.get_env("FLY_REGION", "unknown") 12 | end 13 | 14 | def topic do 15 | "count" 16 | end 17 | 18 | def start_link(_opts) do 19 | GenServer.start_link(__MODULE__, @start_value, name: @name) 20 | end 21 | 22 | def incr() do 23 | GenServer.call @name, :incr 24 | end 25 | 26 | def decr() do 27 | GenServer.call @name, :decr 28 | end 29 | 30 | def current() do 31 | GenServer.call @name, :current 32 | end 33 | 34 | def init(start_count) do 35 | {:ok, start_count} 36 | end 37 | 38 | def handle_call(:current, _from, count) do 39 | {:reply, count, count} 40 | end 41 | 42 | def handle_call(:incr, _from, count) do 43 | make_change(count, +1) 44 | end 45 | 46 | def handle_call(:decr, _from, count) do 47 | make_change(count, -1) 48 | end 49 | 50 | defp make_change(count, change) do 51 | new_count = count + change 52 | PubSub.broadcast(LiveViewCounter.PubSub, topic(), {:count, new_count, :region, fly_region()}) 53 | {:reply, new_count, new_count} 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /lib/live_view_counter/presence.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounter.Presence do 2 | use Phoenix.Presence, 3 | otp_app: :live_view_counter, 4 | pubsub_server: LiveViewCounter.PubSub 5 | end 6 | -------------------------------------------------------------------------------- /lib/live_view_counter_web.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounterWeb 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 LiveViewCounterWeb, :controller 9 | use LiveViewCounterWeb, :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: LiveViewCounterWeb 23 | 24 | import Plug.Conn 25 | import LiveViewCounterWeb.Gettext 26 | alias LiveViewCounterWeb.Router.Helpers, as: Routes 27 | 28 | import Phoenix.LiveView.Controller 29 | end 30 | end 31 | 32 | def view do 33 | quote do 34 | use Phoenix.View, 35 | root: "lib/live_view_counter_web/templates", 36 | namespace: LiveViewCounterWeb 37 | 38 | # Import convenience functions from controllers 39 | import Phoenix.Controller, 40 | only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] 41 | 42 | # Include shared imports and aliases for views 43 | unquote(view_helpers()) 44 | end 45 | end 46 | 47 | def live_view do 48 | quote do 49 | use Phoenix.LiveView, 50 | layout: {LiveViewCounterWeb.LayoutView, "live.html"} 51 | 52 | unquote(view_helpers()) 53 | end 54 | end 55 | 56 | def live_component do 57 | quote do 58 | use Phoenix.LiveComponent 59 | 60 | unquote(view_helpers()) 61 | end 62 | end 63 | 64 | def router do 65 | quote do 66 | use Phoenix.Router 67 | 68 | import Plug.Conn 69 | import Phoenix.Controller 70 | import Phoenix.LiveView.Router 71 | end 72 | end 73 | 74 | def channel do 75 | quote do 76 | use Phoenix.Channel 77 | import LiveViewCounterWeb.Gettext 78 | end 79 | end 80 | 81 | defp view_helpers do 82 | quote do 83 | # Use all HTML functionality (forms, tags, etc) 84 | use Phoenix.HTML 85 | 86 | # Import LiveView helpers (live_render, live_component, live_patch, etc) 87 | import Phoenix.LiveView.Helpers 88 | 89 | # Import basic rendering functionality (render, render_layout, etc) 90 | import Phoenix.View 91 | 92 | import LiveViewCounterWeb.ErrorHelpers 93 | import LiveViewCounterWeb.Gettext 94 | alias LiveViewCounterWeb.Router.Helpers, as: Routes 95 | end 96 | end 97 | 98 | @doc """ 99 | When used, dispatch to the appropriate controller/view/etc. 100 | """ 101 | defmacro __using__(which) when is_atom(which) do 102 | apply(__MODULE__, which, []) 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /lib/live_view_counter_web/channels/user_socket.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounterWeb.UserSocket do 2 | use Phoenix.Socket 3 | 4 | ## Channels 5 | # channel "room:*", LiveViewCounterWeb.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 | # LiveViewCounterWeb.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/live_view_counter_web/endpoint.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounterWeb.Endpoint do 2 | use Phoenix.Endpoint, otp_app: :live_view_counter 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: "_live_view_counter_key", 10 | signing_salt: "PH/r1NMc" 11 | ] 12 | 13 | socket "/socket", LiveViewCounterWeb.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: :live_view_counter, 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 Phoenix.LiveDashboard.RequestLogger, 38 | param_key: "request_logger", 39 | cookie_key: "request_logger" 40 | 41 | plug Plug.RequestId 42 | plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] 43 | 44 | plug Plug.Parsers, 45 | parsers: [:urlencoded, :multipart, :json], 46 | pass: ["*/*"], 47 | json_decoder: Phoenix.json_library() 48 | 49 | plug Plug.MethodOverride 50 | plug Plug.Head 51 | plug Plug.Session, @session_options 52 | plug LiveViewCounterWeb.Router 53 | end 54 | -------------------------------------------------------------------------------- /lib/live_view_counter_web/gettext.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounterWeb.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 LiveViewCounterWeb.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: :live_view_counter 24 | end 25 | -------------------------------------------------------------------------------- /lib/live_view_counter_web/live/counter.ex: -------------------------------------------------------------------------------- 1 | defmodule LiveViewCounterWeb.Counter do 2 | use Phoenix.LiveView 3 | 4 | alias LiveViewCounter.Count 5 | alias Phoenix.PubSub 6 | alias LiveViewCounter.Presence 7 | 8 | @topic Count.topic 9 | @presence_topic "presence" 10 | 11 | def mount(_params, _session, socket) do 12 | PubSub.subscribe(LiveViewCounter.PubSub, @topic) 13 | 14 | Presence.track(self(), @presence_topic, socket.id, %{region: fly_region()}) 15 | LiveViewCounterWeb.Endpoint.subscribe(@presence_topic) 16 | 17 | list = Presence.list(@presence_topic) 18 | present = presence_by_region(list) 19 | counts = Map.new([{fly_region(), Count.current()}]) 20 | 21 | {:ok, assign(socket, counts: counts, present: present, region: fly_region()) } 22 | end 23 | 24 | def fly_region do 25 | System.get_env("FLY_REGION", "unknown") 26 | end 27 | 28 | def handle_event("inc", _, %{ assigns: %{ counts: counts } } = socket) do 29 | c = Count.incr() 30 | {:noreply, assign(socket, counts: Map.put(counts, fly_region(), c))} 31 | end 32 | 33 | def handle_event("dec", _, %{ assigns: %{ counts: counts } } = socket) do 34 | c = Count.decr() 35 | {:noreply, assign(socket, counts: Map.put(counts, fly_region(), c))} 36 | end 37 | 38 | def handle_event("ping", _, socket) do 39 | {:reply, %{}, socket} 40 | end 41 | 42 | def handle_info( 43 | {:count, count, :region, region}, 44 | %{ assigns: %{ counts: counts } } = socket 45 | ) do 46 | 47 | new_counts = Map.put(counts, region, count) 48 | 49 | {:noreply, assign(socket, counts: new_counts)} 50 | end 51 | 52 | def handle_info( 53 | %{event: "presence_diff", payload: %{joins: joins, leaves: leaves}}, 54 | %{assigns: %{present: present}} = socket 55 | ) do 56 | 57 | adds = presence_by_region(joins) 58 | subtracts = presence_by_region(leaves) 59 | 60 | new_present = Map.merge(present, adds, fn _k, v1, v2 -> 61 | v1 + v2 62 | end) 63 | 64 | new_present = Map.merge(new_present, subtracts, fn _k, v1, v2 -> 65 | v1 - v2 66 | end) 67 | 68 | 69 | {:noreply, assign(socket, :present, new_present)} 70 | end 71 | 72 | @type presence_entry :: {any(), %{metas: list(%{ atom() => any() })}} 73 | @spec presence_by_region(list(presence_entry)) :: %{any() => non_neg_integer()} 74 | def presence_by_region(presence) do 75 | result = presence 76 | |> Enum.map(&(elem(&1,1))) 77 | |> Enum.flat_map(&Map.get(&1, :metas)) 78 | |> Enum.filter(&Map.has_key?(&1, :region)) 79 | |> Enum.group_by(&Map.get(&1, :region)) 80 | |> Enum.sort_by(&(elem(&1, 0))) 81 | |> Map.new(fn {k,v}-> {k, length(v) } end) 82 | 83 | result 84 | end 85 | 86 | def render(assigns) do 87 | ~L""" 88 |
89 |

The count is: <%= Map.values(@counts) |> Enum.sum %>

90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | <%= for {k, v} <- @present do %> 100 | 101 | 105 | 106 | 107 | 108 | <% end %> 109 |
RegionUsersClicks
102 | 103 | <%= k %> 104 | <%= v %><%= Map.get(@counts, to_string(k), 0) %>
110 |
111 |
112 | Latency 113 |
114 |
115 | Connected to <%= @region || "?" %> 116 |
117 | """ 118 | end 119 | end 120 | 121 | #