diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b24d71e --- /dev/null +++ b/.gitignore @@ -0,0 +1,50 @@ +# These are some examples of commonly ignored file patterns. +# You should customize this list as applicable to your project. +# Learn more about .gitignore: +# https://www.atlassian.com/git/tutorials/saving-changes/gitignore + +# Node artifact files +node_modules/ +dist/ + +# Compiled Java class files +*.class + +# Compiled Python bytecode +*.py[cod] + +# Log files +*.log + +# Package files +*.jar + +# Maven +target/ +dist/ + +# JetBrains IDE +.idea/ + +# Unit test reports +TEST*.xml + +# Generated by MacOS +.DS_Store + +# Generated by Windows +Thumbs.db + +# Applications +*.app +*.exe +*.war + +# Large media files +*.mp4 +*.tiff +*.avi +*.flv +*.mov +*.wmv + diff --git a/README.md b/README.md index 7756b9a..ba5d1ca 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,35 @@ -# Vendor Scheduler Service Golang +# README # +This repo is meant to be a drop-in replacement for the [vendor-scheduler-service](https://bitbucket.org/outfrontmedia/vendor-scheduler-service/src/master/) built in Ruby. It is part of the overall [programmatic design](https://outfrontmedia.atlassian.net/wiki/spaces/OSP/pages/3008430113/Engineering+Design+for+Programmatic) for ONEX. +## Dependencies -## Getting started +[RabbitMQ](https://www.rabbitmq.com) is used as the message queue for communication from and to ONEX. +For local development, you can use the Docker image by running this command: -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.com/ukacorp/vozovi/vendor-scheduler-service-golang.git -git branch -M main -git push -uf origin main +```shell +docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management ``` -## Integrate with your tools +After running, that you can access the management interface at http://localhost:15672 using the user name and password of `guest`. -- [ ] [Set up project integrations](https://gitlab.com/ukacorp/vozovi/vendor-scheduler-service-golang/-/settings/integrations) +## Benchmark process -## Collaborate with your team +> NOTE: Make sure `ulimit -n` is set appropriately. For example, if you expect to have 1000 concurrent connections, it should be higher than that. -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +`fake_server` is a simple web server that returns a JSON response in a randomized time of 200 - 800 milliseconds. +You can adjust that interval to experiment with different upstream API response times. -## Test and Deploy +`go run fake_server/fake_server.go` -Use the built-in continuous integration in GitLab. +`fill_queue` will seed 15,000 simulated ONEX messages on the queue. You can adjust this number as needed +`ONEX_QUEUE_URL="amqp://guest:guest@localhost:5672/" go run fillqueue/main.go` -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +`main.go` pulls messages off the queue and makes a call to the fake server for each one. +You can tweak the number of queued messages and the maximum number of parallel HTTP connections. +`ONEX_QUEUE_URL="amqp://guest:guest@localhost:5672/" VISTAR_API_URL="http://localhost:8090" go run vendorscheduler/main.go` -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +* Database configuration +* How to run tests +* Load testing +* Deployment instructions diff --git a/cmd/fakeserver/main.go b/cmd/fakeserver/main.go new file mode 100644 index 0000000..6bbf309 --- /dev/null +++ b/cmd/fakeserver/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "log" + "math/rand" + "net/http" + "time" +) + +func fakeHandler(w http.ResponseWriter, req *http.Request) { + n := 200 + rand.Intn(600) // 200 - 800 + time.Sleep(time.Duration(n) * time.Millisecond) + + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"time": %d}`, n) + log.Printf("Response time: %dms", n) +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + http.HandleFunc("/", fakeHandler) + + http.ListenAndServe(":8090", nil) +} diff --git a/cmd/fillqueue/main.go b/cmd/fillqueue/main.go new file mode 100644 index 0000000..f3a7931 --- /dev/null +++ b/cmd/fillqueue/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "bitbucket.org/outfrontmedia/vendor-scheduler-service-golang/internal/pkg/onexqueue" + "encoding/json" + "github.com/streadway/amqp" + "log" + "os" + "time" +) + +func main() { + defer func(start time.Time) { + elapsed := time.Since(start) + log.Printf("fillqueue.main took %s", elapsed) + }(time.Now()) + + conn, ch := onexqueue.Connect(os.Getenv("ONEX_QUEUE_URL")) + defer conn.Close() + defer ch.Close() + + queue := onexqueue.CreateQueueIfNecessary(ch, "hello") + + for i := 1; i <= 15000; i++ { + message := &onexqueue.Message{ + Vendor: "vistar", + Params: onexqueue.MessageParams{ + Player: "79102Z02000392500033J2000", + VenueId: "AT0000112", + DisplayTime: time.Now().Unix(), + DisplayArea: onexqueue.DisplayAreaParam{ + Width: 600, + Height: 900, + }, + }, + } + body, _ := json.Marshal(message) + err := ch.Publish( + "", // exchange + queue.Name, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "application/json", + Body: body, + }) + if err != nil { + log.Fatalf("Failed to publish a message: %s", err) + } + } +} diff --git a/cmd/vendorscheduler/main.go b/cmd/vendorscheduler/main.go new file mode 100644 index 0000000..efa685c --- /dev/null +++ b/cmd/vendorscheduler/main.go @@ -0,0 +1,106 @@ +package main + +import ( + "bitbucket.org/outfrontmedia/vendor-scheduler-service-golang/internal/pkg/onexqueue" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "sync" + "time" +) + +var netClient = &http.Client{} + +func init() { + tr := &http.Transport{ + MaxIdleConns: 0, + MaxIdleConnsPerHost: 0, + } + netClient = &http.Client{Transport: tr} +} + +var numberMessagesToProcess = 15000 +var maxConnections = 500 + +func main() { + defer func(start time.Time) { + elapsed := time.Since(start) + log.Printf("vendorscheduler.main took %s", elapsed) + }(time.Now()) + + conn, ch := onexqueue.Connect(os.Getenv("ONEX_QUEUE_URL")) + defer conn.Close() + defer ch.Close() + + messages := onexqueue.Consume(ch, "hello") + + apiWork := make(chan onexqueue.Message) + apiResults := make(chan string) + + go func() { + for { + result, ok := <-apiResults + if !ok { + return + } + log.Print(result) + } + }() + + wg := sync.WaitGroup{} + for i := 0; i < maxConnections; i++ { + wg.Add(1) + go func() { + for { + work, ok := <-apiWork + if !ok { + wg.Done() + return + } + + _ = work + + CallVistarAPI(apiResults) + } + }() + } + + queueCount := 0 + for d := range messages { + queueCount++ + msg := onexqueue.Message{} + _ = json.Unmarshal(d.Body, &msg) + log.Printf("Received message %d", queueCount) + + apiWork <- msg + + if numberMessagesToProcess == queueCount { + break + } + } + close(apiWork) + + wg.Wait() + close(apiResults) +} + +func CallVistarAPI(apiResults chan string) { + r, err := netClient.Get(os.Getenv("VISTAR_API_URL")) + if err != nil { + apiResults <- fmt.Sprintf("ERROR: %s", err) + return + } + + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + apiResults <- fmt.Sprintf("%s", err) + return + } + + apiResults <- fmt.Sprintf("Response received: %v", string(body)) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ecd3bc9 --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module bitbucket.org/outfrontmedia/vendor-scheduler-service-golang + +go 1.17 + +require ( + github.com/streadway/amqp v1.0.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..75f2157 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= diff --git a/internal/pkg/onexqueue/onexqueue.go b/internal/pkg/onexqueue/onexqueue.go new file mode 100644 index 0000000..8d87411 --- /dev/null +++ b/internal/pkg/onexqueue/onexqueue.go @@ -0,0 +1,71 @@ +package onexqueue + +import ( + "github.com/streadway/amqp" + "log" +) + +type DisplayAreaParam struct { + Width int + Height int +} + +type MessageParams struct { + Player string + VenueId string + DisplayTime int64 + DisplayArea DisplayAreaParam +} + +type Message struct { + Vendor string + Params MessageParams +} + +func Connect(queueUrl string) (*amqp.Connection, *amqp.Channel) { + conn, err := amqp.Dial(queueUrl) + if err != nil { + log.Fatalf("Failed to connect to RabbitMQ: %s", err) + } + + ch, err := conn.Channel() + if err != nil { + log.Fatalf("Failed to open a channel: %s", err) + } + + return conn, ch +} + +func CreateQueueIfNecessary(channel *amqp.Channel, queueName string) amqp.Queue { + queue, err := channel.QueueDeclare( + queueName, // name + false, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) + if err != nil { + log.Fatalf("Failed to declare a queue: %s", err) + } + return queue +} + +func Consume(channel *amqp.Channel, queueName string) <-chan amqp.Delivery { + queue := CreateQueueIfNecessary(channel, queueName) + + messages, err := channel.Consume( + queue.Name, // queue + "", // consumer + true, // auto-ack + false, // exclusive + false, // no-local + false, // no-wait + nil, // args + ) + if err != nil { + log.Fatalf("Failed to register a consumer: %s", err) + } + + return messages +}