├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── cmd └── kmm │ └── main.go ├── fly.toml ├── go.mod ├── go.sum ├── model.go ├── model_test.go └── types.go /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: push 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout 10 | uses: actions/checkout@v3 11 | 12 | - name: Setup Go 13 | uses: actions/setup-go@v3 14 | with: 15 | go-version: '1.18' 16 | 17 | - name: Test 18 | run: go test -v -bench=. -benchmem ./... 19 | 20 | - name: Build 21 | run: go build -v 22 | 23 | lint: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v3 28 | 29 | - name: Setup Go 30 | uses: actions/setup-go@v3 31 | with: 32 | go-version: '1.18' 33 | 34 | - name: Lint 35 | uses: golangci/golangci-lint-action@v3 36 | with: 37 | version: latest 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GOOS=$(shell go env GOOS) 2 | GOARCH=$(shell go env GOARCH) 3 | 4 | build: 5 | mkdir -p dist/$(GOOS)-$(GOARCH) 6 | go build -o dist/$(GOOS)-$(GOARCH)/kmm ./cmd/kmm 7 | 8 | zip: 9 | cd dist/$(GOOS)-$(GOARCH) && zip ../$(GOOS)-$(GOARCH).zip kmm 10 | 11 | dist: 12 | GOOS=linux GOARCH=amd64 make build zip 13 | GOOS=darwin GOARCH=amd64 make build zip 14 | GOOS=windows GOARCH=amd64 make build zip 15 | 16 | .PHONY: dist 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kids money manager 2 | 3 | KMM provides a way for kids to learn how to manage money. Money can be (logically) deposited to the account by parents/guardians, and kids can withdraw up to a certain amount per day/week/month that their parent(s) defines. 4 | 5 | *This is a demo application for the series [Implementing an event store on NATS](https://www.byronruth.com/implementing-an-event-store-on-nats-part-2/). It utilizes [rita](https://github.com/bruth/rita) which was developed as part of this series and provides an event store implementation on NATS and various event-centric patterns.* 6 | 7 | -------------------------------------------------------------------------------- /cmd/kmm/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/base64" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io/ioutil" 10 | "log" 11 | "net/http" 12 | "os" 13 | "os/signal" 14 | "strings" 15 | "time" 16 | 17 | "github.com/bruth/kmm" 18 | "github.com/bruth/rita" 19 | "github.com/bruth/rita/testutil" 20 | "github.com/bruth/rita/types" 21 | "github.com/nats-io/jsm.go/natscontext" 22 | "github.com/nats-io/nats.go" 23 | "github.com/nats-io/nuid" 24 | "github.com/urfave/cli/v2" 25 | ) 26 | 27 | var ( 28 | defaultRequestTimeout = 5 * time.Second 29 | 30 | // Initialize the type registry with the application/domain types. 31 | tr, _ = types.NewRegistry(kmm.Types) 32 | 33 | app = &cli.App{ 34 | Name: "kmm", 35 | Usage: "Kids money manager.", 36 | Commands: []*cli.Command{ 37 | serve, 38 | deposit, 39 | withdraw, 40 | setBudget, 41 | removeBudget, 42 | currentBalance, 43 | lastBudgetPeriod, 44 | ledger, 45 | }, 46 | } 47 | 48 | natsFlags = []cli.Flag{ 49 | &cli.StringFlag{ 50 | Name: "nats.url", 51 | Value: "", 52 | Usage: "NATS server URL(s).", 53 | EnvVars: []string{"NATS_URL"}, 54 | }, 55 | &cli.StringFlag{ 56 | Name: "nats.creds", 57 | Value: "", 58 | Usage: "NATS credentials file.", 59 | EnvVars: []string{"NATS_CREDS"}, 60 | }, 61 | &cli.StringFlag{ 62 | Name: "nats.context", 63 | Value: natscontext.SelectedContext(), 64 | Usage: "NATS context name.", 65 | EnvVars: []string{"NATS_CONTEXT"}, 66 | }, 67 | } 68 | 69 | serve = &cli.Command{ 70 | Name: "serve", 71 | Usage: "Run the server.", 72 | Flags: append([]cli.Flag{ 73 | &cli.BoolFlag{ 74 | Name: "nats.embed", 75 | Value: false, 76 | Usage: "Run NATS as an embedded server for testing.", 77 | EnvVars: []string{"NATS_EMBED"}, 78 | }, 79 | &cli.StringFlag{ 80 | Name: "http.addr", 81 | Value: "127.0.0.1:8080", 82 | Usage: "HTTP bind address.", 83 | EnvVars: []string{"HTTP_ADDR"}, 84 | }, 85 | }, natsFlags...), 86 | Action: func(c *cli.Context) error { 87 | return runServer(c) 88 | }, 89 | } 90 | 91 | deposit = &cli.Command{ 92 | Name: "deposit", 93 | Usage: "Deposit money into an account.", 94 | Flags: natsFlags, 95 | ArgsUsage: " []", 96 | Action: func(c *cli.Context) error { 97 | n := c.NArg() 98 | if n < 2 { 99 | return fmt.Errorf("account and amount are required") 100 | } else if n > 3 { 101 | return fmt.Errorf("at most three arguments are supported") 102 | } 103 | 104 | account := c.Args().Get(0) 105 | amount := c.Args().Get(1) 106 | description := c.Args().Get(2) 107 | 108 | nc, err := connectNats(c) 109 | if err != nil { 110 | return err 111 | } 112 | defer nc.Drain() //nolint 113 | 114 | subject := fmt.Sprintf("kmm.services.%s.deposit-funds", account) 115 | data, _ := json.Marshal(map[string]string{ 116 | "Amount": amount, 117 | "Description": description, 118 | }) 119 | 120 | rep, err := nc.Request(subject, data, defaultRequestTimeout) 121 | if err != nil { 122 | return err 123 | } 124 | if len(rep.Data) > 0 { 125 | fmt.Println(string(rep.Data)) 126 | } 127 | return nil 128 | }, 129 | } 130 | 131 | withdraw = &cli.Command{ 132 | Name: "withdraw", 133 | Usage: "Withdraw money from an account.", 134 | Flags: natsFlags, 135 | ArgsUsage: " []", 136 | Action: func(c *cli.Context) error { 137 | n := c.NArg() 138 | if n < 2 { 139 | return fmt.Errorf("account and amount are required") 140 | } else if n > 3 { 141 | return fmt.Errorf("at most three arguments are supported") 142 | } 143 | 144 | account := c.Args().Get(0) 145 | amount := c.Args().Get(1) 146 | description := c.Args().Get(2) 147 | 148 | nc, err := connectNats(c) 149 | if err != nil { 150 | return err 151 | } 152 | defer nc.Drain() //nolint 153 | 154 | subject := fmt.Sprintf("kmm.services.%s.withdraw-funds", account) 155 | data, _ := json.Marshal(map[string]string{ 156 | "Amount": amount, 157 | "Description": description, 158 | }) 159 | 160 | rep, err := nc.Request(subject, data, defaultRequestTimeout) 161 | if err != nil { 162 | return err 163 | } 164 | if len(rep.Data) > 0 { 165 | fmt.Println(string(rep.Data)) 166 | } 167 | return nil 168 | }, 169 | } 170 | 171 | setBudget = &cli.Command{ 172 | Name: "set-budget", 173 | Usage: "Set a budget on an account.", 174 | Flags: natsFlags, 175 | ArgsUsage: " ", 176 | Action: func(c *cli.Context) error { 177 | n := c.NArg() 178 | if n != 3 { 179 | return fmt.Errorf("account, amount, and period are required") 180 | } 181 | 182 | account := c.Args().Get(0) 183 | amount := c.Args().Get(1) 184 | period := c.Args().Get(2) 185 | 186 | nc, err := connectNats(c) 187 | if err != nil { 188 | return err 189 | } 190 | defer nc.Drain() //nolint 191 | 192 | subject := fmt.Sprintf("kmm.services.%s.set-budget", account) 193 | data, _ := json.Marshal(map[string]string{ 194 | "MaxAmount": amount, 195 | "Period": period, 196 | }) 197 | 198 | rep, err := nc.Request(subject, data, defaultRequestTimeout) 199 | if err != nil { 200 | return err 201 | } 202 | if len(rep.Data) > 0 { 203 | fmt.Println(string(rep.Data)) 204 | } 205 | return nil 206 | }, 207 | } 208 | 209 | removeBudget = &cli.Command{ 210 | Name: "remove-budget", 211 | Usage: "Removes a budget from an account.", 212 | Flags: natsFlags, 213 | ArgsUsage: "", 214 | Action: func(c *cli.Context) error { 215 | n := c.NArg() 216 | if n != 1 { 217 | return fmt.Errorf("account required") 218 | } 219 | 220 | account := c.Args().Get(0) 221 | 222 | nc, err := connectNats(c) 223 | if err != nil { 224 | return err 225 | } 226 | defer nc.Drain() //nolint 227 | 228 | subject := fmt.Sprintf("kmm.services.%s.remove-budget", account) 229 | rep, err := nc.Request(subject, []byte{}, defaultRequestTimeout) 230 | if err != nil { 231 | return err 232 | } 233 | if len(rep.Data) > 0 { 234 | fmt.Println(string(rep.Data)) 235 | } 236 | return nil 237 | }, 238 | } 239 | 240 | currentBalance = &cli.Command{ 241 | Name: "balance", 242 | Usage: "Gets the current balance for an account.", 243 | Flags: natsFlags, 244 | ArgsUsage: "", 245 | Action: func(c *cli.Context) error { 246 | n := c.NArg() 247 | if n != 1 { 248 | return fmt.Errorf("account required") 249 | } 250 | 251 | account := c.Args().Get(0) 252 | 253 | nc, err := connectNats(c) 254 | if err != nil { 255 | return err 256 | } 257 | defer nc.Drain() //nolint 258 | 259 | subject := fmt.Sprintf("kmm.services.%s.balance", account) 260 | rep, err := nc.Request(subject, []byte{}, defaultRequestTimeout) 261 | if err != nil { 262 | return err 263 | } 264 | v, err := tr.UnmarshalType(rep.Data, "current-funds") 265 | if err != nil { 266 | return err 267 | } 268 | funds, _ := v.(*kmm.CurrentFunds) 269 | fmt.Println(funds.Amount) 270 | return nil 271 | }, 272 | } 273 | 274 | ledger = &cli.Command{ 275 | Name: "ledger", 276 | Usage: "Subscribes to the account ledger.", 277 | Flags: natsFlags, 278 | ArgsUsage: "", 279 | Action: func(c *cli.Context) error { 280 | n := c.NArg() 281 | if n != 1 { 282 | return fmt.Errorf("account required") 283 | } 284 | 285 | account := c.Args().Get(0) 286 | 287 | nc, err := connectNats(c) 288 | if err != nil { 289 | return err 290 | } 291 | defer nc.Drain() //nolint 292 | 293 | rt, _ := rita.New(nc, rita.TypeRegistry(tr)) 294 | 295 | streamID := nuid.Next() 296 | streamSubject := fmt.Sprintf("kmm.streams.%s", streamID) 297 | 298 | sub, err := nc.Subscribe(streamSubject, func(msg *nats.Msg) { 299 | event, err := rt.UnpackEvent(msg) 300 | if err != nil { 301 | log.Print(err) 302 | return 303 | } 304 | 305 | switch e := event.Data.(type) { 306 | case *kmm.FundsDeposited: 307 | if e.Description == "" { 308 | fmt.Printf("+%s | %s\n", e.Amount, e.Time.Format(time.ANSIC)) 309 | } else { 310 | fmt.Printf("+%s | %s | %s\n", e.Amount, e.Time.Format(time.ANSIC), e.Description) 311 | } 312 | case *kmm.FundsWithdrawn: 313 | if e.Description == "" { 314 | fmt.Printf("-%s | %s\n", e.Amount, e.Time.Format(time.ANSIC)) 315 | } else { 316 | fmt.Printf("-%s | %s | %s\n", e.Amount, e.Time.Format(time.ANSIC), e.Description) 317 | } 318 | } 319 | }) 320 | if err != nil { 321 | return fmt.Errorf("ledger-subscribe: %w", err) 322 | } 323 | defer sub.Unsubscribe() //nolint 324 | 325 | subject := fmt.Sprintf("kmm.services.%s.ledger", account) 326 | _, err = nc.Request(subject, []byte(fmt.Sprintf(`{"id": "%s"}`, streamID)), defaultRequestTimeout) 327 | if err != nil { 328 | return fmt.Errorf("ledger-request: %w", err) 329 | } 330 | 331 | sigch := make(chan os.Signal, 1) 332 | signal.Notify(sigch, os.Interrupt) 333 | <-sigch 334 | 335 | return nil 336 | }, 337 | } 338 | 339 | lastBudgetPeriod = &cli.Command{ 340 | Name: "last-budget-period", 341 | Usage: "Gets the summary for the last active budget period.", 342 | Flags: natsFlags, 343 | ArgsUsage: "", 344 | Action: func(c *cli.Context) error { 345 | n := c.NArg() 346 | if n != 1 { 347 | return fmt.Errorf("account required") 348 | } 349 | 350 | account := c.Args().Get(0) 351 | 352 | nc, err := connectNats(c) 353 | if err != nil { 354 | return err 355 | } 356 | defer nc.Drain() //nolint 357 | 358 | subject := fmt.Sprintf("kmm.services.%s.last-budget-period", account) 359 | rep, err := nc.Request(subject, []byte{}, defaultRequestTimeout) 360 | if err != nil { 361 | return err 362 | } 363 | v, err := tr.UnmarshalType(rep.Data, "budget-period") 364 | if err != nil { 365 | return err 366 | } 367 | s, _ := v.(*kmm.BudgetPeriod) 368 | 369 | if s.PolicyMaxWithdrawAmount.IsZero() { 370 | fmt.Println("no budget set") 371 | return nil 372 | } 373 | 374 | fmt.Printf(`period start: %s 375 | period end: %s 376 | withdrawals: %d 377 | total withdrawn: %s 378 | `, s.PeriodStartTime.Format(time.ANSIC), s.NextPeriodStartTime.Format(time.ANSIC), s.WithdrawalsInPeriod, s.FundsWithdrawnInPeriod) 379 | return nil 380 | }, 381 | } 382 | ) 383 | 384 | func connectNats(c *cli.Context) (*nats.Conn, error) { 385 | natsUrl := c.String("nats.url") 386 | natsCreds := c.String("nats.creds") 387 | natsContext := c.String("nats.context") 388 | 389 | // Setup NATS connection depending on the values available. 390 | if natsCreds == "" && os.Getenv("NATS_CREDS_B64") != "" { 391 | // Hack to get the get the creds file content as a Fly.io secret.. 392 | var err error 393 | natsCreds, err = decodeUserCredsToFile(os.Getenv("NATS_CREDS_B64")) 394 | if err != nil { 395 | return nil, err 396 | } 397 | } 398 | 399 | var copts []nats.Option 400 | if natsCreds != "" { 401 | copts = append(copts, nats.UserCredentials(natsCreds)) 402 | } 403 | 404 | if natsContext != "" { 405 | return natscontext.Connect(natsContext, copts...) 406 | } 407 | 408 | return nats.Connect(natsUrl, copts...) 409 | } 410 | 411 | func main() { 412 | if err := app.Run(os.Args); err != nil { 413 | log.SetFlags(0) 414 | log.Print(err) 415 | } 416 | } 417 | 418 | func decodeUserCredsToFile(s string) (string, error) { 419 | b, err := base64.StdEncoding.DecodeString(s) 420 | if err != nil { 421 | return "", err 422 | } 423 | f, err := ioutil.TempFile("", "") 424 | if err != nil { 425 | return "", err 426 | } 427 | _, err = f.Write(b) 428 | if err != nil { 429 | return "", err 430 | } 431 | return f.Name(), f.Close() 432 | } 433 | 434 | func runServer(c *cli.Context) error { 435 | natsEmbed := c.Bool("nats.embed") 436 | httpAddr := c.String("http.addr") 437 | 438 | var ( 439 | nc *nats.Conn 440 | err error 441 | ) 442 | 443 | if natsEmbed { 444 | ns := testutil.NewNatsServer(4837) 445 | defer ns.Shutdown() 446 | nc, err = nats.Connect(ns.ClientURL()) 447 | } else { 448 | nc, err = connectNats(c) 449 | } 450 | if err != nil { 451 | return err 452 | } 453 | defer nc.Drain() //nolint 454 | 455 | js, err := nc.JetStream() 456 | if err != nil { 457 | return err 458 | } 459 | 460 | // Initialize a new Rita instance. 461 | rt, err := rita.New(nc, rita.TypeRegistry(tr)) 462 | if err != nil { 463 | return err 464 | } 465 | 466 | // Create an event store. (this is idempotent) 467 | es := rt.EventStore("kmm") 468 | if natsEmbed { 469 | _ = es.Delete() 470 | } 471 | err = es.Create(&nats.StreamConfig{ 472 | Subjects: []string{"kmm.events.>"}, 473 | MaxBytes: 512 * 1000 * 1000, // 512MiB 474 | }) 475 | if err != nil { 476 | return err 477 | } 478 | 479 | handleCommand := func(ctx context.Context, msg *nats.Msg, account, operation string) (any, error) { 480 | // Unmarshal the command based on the type. 481 | cmd, err := tr.UnmarshalType(msg.Data, operation) 482 | if err != nil { 483 | if err == types.ErrTypeNotRegistered { 484 | return nil, fmt.Errorf("unknown command: %s", operation) 485 | } 486 | return nil, err 487 | } 488 | 489 | if v, ok := cmd.(interface{ Validate() error }); ok { 490 | if err := v.Validate(); err != nil { 491 | return nil, err 492 | } 493 | } 494 | 495 | subject := fmt.Sprintf("kmm.events.accounts.%s", account) 496 | 497 | // Initialize the aggregate and evolve the state. 498 | a := kmm.NewAccount() 499 | seq, err := es.Evolve(ctx, subject, a) 500 | if err != nil { 501 | return nil, err 502 | } 503 | 504 | // Decide if accepted and the resulting events. 505 | // TODO: extract out additional headers as command fields, e.g. rita-command-id 506 | events, err := a.Decide(&rita.Command{ 507 | Data: cmd, 508 | }) 509 | if err != nil { 510 | return nil, err 511 | } 512 | 513 | // Append new events. 514 | _, err = es.Append(ctx, subject, events, rita.ExpectSequence(seq)) 515 | if err != nil { 516 | return nil, err 517 | } 518 | 519 | return nil, nil 520 | } 521 | 522 | handleCurrentFundsQuery := func(ctx context.Context, msg *nats.Msg, account string) (any, error) { 523 | var s kmm.CurrentFunds 524 | 525 | subject := fmt.Sprintf("kmm.events.accounts.%s", account) 526 | _, err := es.Evolve(ctx, subject, &s) 527 | if err != nil { 528 | return nil, err 529 | } 530 | 531 | return &s, nil 532 | } 533 | 534 | handleBudgetSummaryQuery := func(ctx context.Context, msg *nats.Msg, account string) (any, error) { 535 | var s kmm.BudgetPeriod 536 | 537 | subject := fmt.Sprintf("kmm.events.accounts.%s", account) 538 | _, err := es.Evolve(ctx, subject, &s) 539 | if err != nil { 540 | return nil, err 541 | } 542 | 543 | return &s, nil 544 | } 545 | 546 | handleLedgerQuery := func(ctx context.Context, msg *nats.Msg, account string) (any, error) { 547 | var m map[string]string 548 | _ = json.Unmarshal(msg.Data, &m) 549 | subject := fmt.Sprintf("kmm.streams.%s", m["id"]) 550 | 551 | _, err := js.AddConsumer("kmm", &nats.ConsumerConfig{ 552 | DeliverSubject: subject, 553 | DeliverPolicy: nats.DeliverAllPolicy, 554 | FilterSubject: fmt.Sprintf("kmm.events.accounts.%s", account), 555 | InactiveThreshold: 5 * time.Second, 556 | AckPolicy: nats.AckNonePolicy, 557 | }) 558 | if err != nil { 559 | return nil, err 560 | } 561 | 562 | return json.Marshal(map[string]string{ 563 | "subject": subject, 564 | }) 565 | } 566 | 567 | respondMsg := func(msg *nats.Msg, result any, err error) { 568 | if err != nil { 569 | _ = msg.Respond([]byte(err.Error())) 570 | return 571 | } 572 | 573 | if result == nil { 574 | _ = msg.Respond(nil) 575 | return 576 | } 577 | 578 | // If bytes, respond directly. 579 | if b, ok := result.([]byte); ok { 580 | _ = msg.Respond(b) 581 | return 582 | } 583 | 584 | // Otherwise assume its part of the type registry. 585 | b, err := tr.Marshal(result) 586 | if err != nil { 587 | _ = msg.Respond([]byte(err.Error())) 588 | } else { 589 | _ = msg.Respond(b) 590 | } 591 | } 592 | 593 | // Service to handle services (request/reply). 594 | sub1, err := nc.QueueSubscribe("kmm.services.*.*", "services", func(msg *nats.Msg) { 595 | ctx := context.Background() 596 | 597 | // Extract out account and command from subject. 598 | toks := strings.Split(msg.Subject, ".") 599 | 600 | // Parse out the account ID and operation. 601 | account := toks[2] 602 | operation := toks[3] 603 | 604 | var ( 605 | result any 606 | err error 607 | ) 608 | 609 | switch operation { 610 | // Commands. 611 | case "deposit-funds", "withdraw-funds", "set-budget", "remove-budget": 612 | result, err = handleCommand(ctx, msg, account, operation) 613 | 614 | // Queries. 615 | case "balance": 616 | result, err = handleCurrentFundsQuery(ctx, msg, account) 617 | 618 | case "last-budget-period": 619 | result, err = handleBudgetSummaryQuery(ctx, msg, account) 620 | 621 | case "ledger": 622 | result, err = handleLedgerQuery(ctx, msg, account) 623 | 624 | default: 625 | err = errors.New("unknown service operation") 626 | } 627 | 628 | // Respond with result, error, or nil. 629 | respondMsg(msg, result, err) 630 | }) 631 | if err != nil { 632 | return err 633 | } 634 | defer sub1.Unsubscribe() //nolint 635 | 636 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 637 | msg := fmt.Sprintf(`Kids Money Manager - hosted on Fly.io, connected with Synadia's NGS 638 | Connect %s 639 | `, nc.ConnectedUrl()) 640 | w.Write([]byte(msg)) //nolint 641 | }) 642 | 643 | return http.ListenAndServe(httpAddr, nil) 644 | } 645 | -------------------------------------------------------------------------------- /fly.toml: -------------------------------------------------------------------------------- 1 | # fly.toml file generated for kmm on 2022-05-31T10:14:39-04:00 2 | 3 | app = "kmm" 4 | 5 | kill_signal = "SIGINT" 6 | kill_timeout = 5 7 | processes = [] 8 | 9 | [build] 10 | builder = "paketobuildpacks/builder:base" 11 | buildpacks = ["gcr.io/paketo-buildpacks/go"] 12 | [build.args] 13 | BP_GO_TARGETS = "./cmd/kmm" 14 | 15 | [env] 16 | PORT = "8080" 17 | NATS_URL = "tls://connect.ngs.global" 18 | 19 | [experimental] 20 | allowed_public_ports = [] 21 | auto_rollback = true 22 | cmd = ["kmm", "serve", "--http.addr=0.0.0.0:8080"] 23 | 24 | [[services]] 25 | http_checks = [] 26 | internal_port = 8080 27 | processes = ["app"] 28 | protocol = "tcp" 29 | script_checks = [] 30 | 31 | [services.concurrency] 32 | hard_limit = 25 33 | soft_limit = 20 34 | type = "connections" 35 | 36 | [[services.ports]] 37 | force_https = true 38 | handlers = ["http"] 39 | port = 80 40 | 41 | [[services.ports]] 42 | handlers = ["tls", "http"] 43 | port = 443 44 | 45 | [[services.tcp_checks]] 46 | grace_period = "1s" 47 | interval = "15s" 48 | restart_limit = 0 49 | timeout = "2s" 50 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/bruth/kmm 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/bruth/rita v0.0.0-20220531120824-03122ba95b83 7 | github.com/nats-io/jsm.go v0.0.31 8 | github.com/nats-io/nats.go v1.16.0 9 | github.com/nats-io/nuid v1.0.1 10 | github.com/shopspring/decimal v1.3.1 11 | github.com/urfave/cli/v2 v2.8.1 12 | ) 13 | 14 | require ( 15 | github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect 16 | github.com/golang/protobuf v1.5.2 // indirect 17 | github.com/google/go-cmp v0.5.8 // indirect 18 | github.com/google/uuid v1.3.0 // indirect 19 | github.com/klauspost/compress v1.15.1 // indirect 20 | github.com/minio/highwayhash v1.0.2 // indirect 21 | github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a // indirect 22 | github.com/nats-io/nats-server/v2 v2.8.2 // indirect 23 | github.com/nats-io/nkeys v0.3.0 // indirect 24 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 25 | github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect 26 | github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect 27 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect 28 | golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect 29 | golang.org/x/sys v0.0.0-20220111092808-5a964db01320 // indirect 30 | golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 // indirect 31 | google.golang.org/protobuf v1.28.0 // indirect 32 | ) 33 | 34 | //replace github.com/bruth/rita => /home/byron/go/src/github.com/bruth/rita2 35 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/bruth/rita v0.0.0-20220531120824-03122ba95b83 h1:suPVTwGmGhe8l6fGTIoIvqdkghVosGmZ5Qmo+sWHh0M= 2 | github.com/bruth/rita v0.0.0-20220531120824-03122ba95b83/go.mod h1:2V/AyiuuRcdj0/n27Wld2LcDEAXOBXb0+NMt9eAD6OM= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= 4 | github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 5 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 6 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 7 | github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= 8 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 9 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 10 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 11 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 12 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 13 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 14 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 15 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 16 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 17 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 18 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 19 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 20 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 21 | github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= 22 | github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= 23 | github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 24 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 25 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 26 | github.com/klauspost/compress v1.14.4/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= 27 | github.com/klauspost/compress v1.15.1 h1:y9FcTHGyrebwfP0ZZqFiaxTaiDnUrGkJkI+f583BL1A= 28 | github.com/klauspost/compress v1.15.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= 29 | github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= 30 | github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= 31 | github.com/nats-io/jsm.go v0.0.31 h1:ARmf+Kic6G8E5imOkfIhwEuBlEbxlW9nb2PRWx0XDUU= 32 | github.com/nats-io/jsm.go v0.0.31/go.mod h1:LVb1bL1houzsI3nySNW/Omhg+d2kKnMHrgpNGcRMp8M= 33 | github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a h1:lem6QCvxR0Y28gth9P+wV2K/zYUUAkJ+55U8cpS0p5I= 34 | github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a/go.mod h1:0tqz9Hlu6bCBFLWAASKhE5vUA4c24L9KPUUgvwumE/k= 35 | github.com/nats-io/nats-server/v2 v2.7.5-0.20220415000625-a6b62f61a703/go.mod h1:5vic7C58BFEVltiZhs7Kq81q2WcEPhJPsmNv1FOrdv0= 36 | github.com/nats-io/nats-server/v2 v2.8.2 h1:5m1VytMEbZx0YINvKY+X2gXdLNwP43uLXnFRwz8j8KE= 37 | github.com/nats-io/nats-server/v2 v2.8.2/go.mod h1:vIdpKz3OG+DCg4q/xVPdXHoztEyKDWRtykQ4N7hd7C4= 38 | github.com/nats-io/nats.go v1.14.0/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w= 39 | github.com/nats-io/nats.go v1.14.1-0.20220412004736-c75dfd54b52c/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w= 40 | github.com/nats-io/nats.go v1.16.0 h1:zvLE7fGBQYW6MWaFaRdsgm9qT39PJDQoju+DS8KsO1g= 41 | github.com/nats-io/nats.go v1.16.0/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w= 42 | github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8= 43 | github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4= 44 | github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= 45 | github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= 46 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 47 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 48 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 49 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 50 | github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= 51 | github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= 52 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 53 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 54 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 55 | github.com/urfave/cli/v2 v2.8.1 h1:CGuYNZF9IKZY/rfBe3lJpccSoIY1ytfvmgQT90cNOl4= 56 | github.com/urfave/cli/v2 v2.8.1/go.mod h1:Z41J9TPoffeoqP0Iza0YbAhGvymRdZAd2uPmZ5JxRdY= 57 | github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU= 58 | github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= 59 | github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= 60 | github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= 61 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= 62 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= 63 | golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= 64 | golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 65 | golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM= 66 | golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 67 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 68 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 69 | golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 70 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 71 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 72 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 73 | golang.org/x/sys v0.0.0-20220111092808-5a964db01320 h1:0jf+tOCoZ3LyutmCOWpVni1chK4VfFLhRsDK7MhqGRY= 74 | golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 75 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 76 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 77 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 78 | golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 h1:GZokNIeuVkl3aZHJchRrr13WCsols02MLUcz1U9is6M= 79 | golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 80 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 81 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 82 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 83 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 84 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 85 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 86 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 87 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 88 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 89 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 90 | google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= 91 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 92 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 93 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 94 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 95 | -------------------------------------------------------------------------------- /model.go: -------------------------------------------------------------------------------- 1 | package kmm 2 | 3 | import ( 4 | "errors" 5 | "time" 6 | 7 | "github.com/bruth/rita" 8 | "github.com/bruth/rita/clock" 9 | "github.com/shopspring/decimal" 10 | ) 11 | 12 | var ( 13 | ErrUnknownCommand = errors.New("unknown command") 14 | ErrNonZeroAmount = errors.New("kmm: amount must be greater than zero") 15 | ErrInvalidPeriod = errors.New("kmm: period must be minutely, daily, weekly, monthly") 16 | ErrInsufficientFunds = errors.New("kmm: insufficient funds") 17 | ErrExceedWithinPeriod = errors.New("kmm: withdrawal would exceed max amount allowed in current period") 18 | ) 19 | 20 | type DeciderEvolver interface { 21 | rita.Decider 22 | rita.Evolver 23 | } 24 | 25 | var ( 26 | _ DeciderEvolver = &Account{} 27 | _ rita.Evolver = &BudgetPeriod{} 28 | _ rita.Evolver = &CurrentFunds{} 29 | ) 30 | 31 | type DepositFunds struct { 32 | Amount decimal.Decimal 33 | Description string 34 | } 35 | 36 | func (c *DepositFunds) Validate() error { 37 | if c.Amount.LessThanOrEqual(decimal.Zero) { 38 | return ErrNonZeroAmount 39 | } 40 | return nil 41 | } 42 | 43 | type FundsDeposited struct { 44 | Amount decimal.Decimal 45 | Description string 46 | Time time.Time 47 | } 48 | 49 | type WithdrawFunds struct { 50 | Amount decimal.Decimal 51 | Description string 52 | } 53 | 54 | func (c *WithdrawFunds) Validate() error { 55 | if c.Amount.LessThanOrEqual(decimal.Zero) { 56 | return ErrNonZeroAmount 57 | } 58 | return nil 59 | } 60 | 61 | type FundsWithdrawn struct { 62 | Amount decimal.Decimal 63 | Description string 64 | Time time.Time 65 | PeriodChanged bool 66 | } 67 | 68 | type Period string 69 | 70 | const ( 71 | Minutely Period = "minutely" // For demo... 72 | Daily Period = "daily" 73 | Weekly Period = "weekly" 74 | Monthly Period = "monthly" 75 | ) 76 | 77 | type SetBudget struct { 78 | MaxAmount decimal.Decimal 79 | Period Period 80 | } 81 | 82 | func (c *SetBudget) Validate() error { 83 | if c.MaxAmount.LessThan(decimal.Zero) { 84 | return ErrNonZeroAmount 85 | } 86 | 87 | // Validate period. 88 | switch c.Period { 89 | case Minutely, Daily, Weekly, Monthly: 90 | default: 91 | return ErrInvalidPeriod 92 | } 93 | return nil 94 | } 95 | 96 | type BudgetSet struct { 97 | MaxWithdrawAmount decimal.Decimal 98 | Period Period 99 | PolicyStartTime time.Time 100 | PeriodStartTime time.Time 101 | NextPeriodStartTime time.Time 102 | } 103 | 104 | type RemoveBudget struct{} 105 | 106 | type BudgetRemoved struct { 107 | PolicyRemoveTime time.Time 108 | } 109 | 110 | // periodWindow takes the time value and determines the current start time 111 | // of the period and start time of the next period. 112 | func periodWindow(t time.Time, p Period) (time.Time, time.Time) { 113 | switch p { 114 | // Every minute.. 115 | case Minutely: 116 | st := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, t.Location()) 117 | nst := st.Add(time.Minute) 118 | return st, nst 119 | 120 | // Day starts at midnight 121 | case Daily: 122 | // Truncate time. 123 | st := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) 124 | // Add one day. 125 | nst := st.AddDate(0, 0, 1) 126 | return st, nst 127 | 128 | // Week starts on Monday at midnight 129 | case Weekly: 130 | sd := t.Day() - int(t.Weekday()-time.Monday) 131 | st := time.Date(t.Year(), t.Month(), sd, 0, 0, 0, 0, t.Location()) 132 | nst := st.AddDate(0, 0, 7) 133 | return st, nst 134 | 135 | // Month starts the 1st at midnight 136 | case Monthly: 137 | st := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) 138 | nst := st.AddDate(0, 1, 0) 139 | return st, nst 140 | } 141 | 142 | return time.Time{}, time.Time{} 143 | } 144 | 145 | func NewAccount() *Account { 146 | return &Account{ 147 | clock: clock.Time, 148 | } 149 | } 150 | 151 | // Account aggregate which primarily decides on whether a withdrawal is 152 | // allowed given the current funds and if a policy is set. 153 | // 154 | // The DepositFunds command doesn't even need an aggregate since there is no 155 | // validation other than command validation that the amount is a positive value 156 | // (which is done prior to the command being received here). 157 | // 158 | // The Set/RemoveWithdrawPolicy are in the same category and does not really need 159 | // any aggregated state for them to be accepted. 160 | type Account struct { 161 | CurrentFunds decimal.Decimal 162 | 163 | // Policy related. 164 | MaxWithdrawAmount decimal.Decimal 165 | PolicyPeriod Period 166 | PeriodStartTime time.Time 167 | NextPeriodStartTime time.Time 168 | FundsWithdrawnInPeriod decimal.Decimal 169 | 170 | clock clock.Clock 171 | } 172 | 173 | func (a *Account) Decide(command *rita.Command) ([]*rita.Event, error) { 174 | switch c := command.Data.(type) { 175 | case *DepositFunds: 176 | // As much money can be deposited as desired, so no 177 | // decision needs to be made. 178 | return []*rita.Event{ 179 | { 180 | Data: &FundsDeposited{ 181 | Amount: c.Amount, 182 | Description: c.Description, 183 | Time: a.clock.Now(), 184 | }, 185 | }, 186 | }, nil 187 | 188 | case *WithdrawFunds: 189 | // Ensure funds do not go below zero. 190 | if a.CurrentFunds.Sub(c.Amount).LessThan(decimal.Zero) { 191 | return nil, ErrInsufficientFunds 192 | } 193 | 194 | now := a.clock.Now() 195 | 196 | var periodChanged bool 197 | 198 | // Check if the withdraw is allowed given the policy. 199 | if a.PolicyPeriod != "" { 200 | // Next period start time has not been reached. 201 | periodChanged = !now.Before(a.NextPeriodStartTime) 202 | 203 | if !periodChanged { 204 | if a.FundsWithdrawnInPeriod.Add(c.Amount).GreaterThan(a.MaxWithdrawAmount) { 205 | return nil, ErrExceedWithinPeriod 206 | } 207 | } 208 | } 209 | 210 | // Could emit PeriodChanged event as well, however this can be lazily 211 | // detected on the evolve side. Alternatively, an indepedent actor could 212 | // monitor the policy changes and a ticker to emit period change events.. 213 | return []*rita.Event{ 214 | { 215 | Data: &FundsWithdrawn{ 216 | Amount: c.Amount, 217 | Description: c.Description, 218 | Time: now, 219 | PeriodChanged: periodChanged, 220 | }, 221 | }, 222 | }, nil 223 | 224 | case *SetBudget: 225 | now := a.clock.Now() 226 | st, nst := periodWindow(now, c.Period) 227 | 228 | return []*rita.Event{ 229 | { 230 | Data: &BudgetSet{ 231 | MaxWithdrawAmount: c.MaxAmount, 232 | Period: c.Period, 233 | PolicyStartTime: now, 234 | PeriodStartTime: st, 235 | NextPeriodStartTime: nst, 236 | }, 237 | }, 238 | }, nil 239 | 240 | case *RemoveBudget: 241 | return []*rita.Event{ 242 | { 243 | Data: &BudgetRemoved{ 244 | PolicyRemoveTime: a.clock.Now(), 245 | }, 246 | }, 247 | }, nil 248 | } 249 | 250 | return nil, ErrUnknownCommand 251 | } 252 | 253 | func (a *Account) Evolve(event *rita.Event) error { 254 | switch e := event.Data.(type) { 255 | case *FundsDeposited: 256 | a.CurrentFunds = a.CurrentFunds.Add(e.Amount) 257 | 258 | case *FundsWithdrawn: 259 | a.CurrentFunds = a.CurrentFunds.Sub(e.Amount) 260 | 261 | if a.PolicyPeriod != "" { 262 | if e.PeriodChanged { 263 | a.FundsWithdrawnInPeriod = e.Amount 264 | a.PeriodStartTime, a.NextPeriodStartTime = periodWindow(e.Time, a.PolicyPeriod) 265 | } else { 266 | a.FundsWithdrawnInPeriod = a.FundsWithdrawnInPeriod.Add(e.Amount) 267 | } 268 | } 269 | 270 | case *BudgetSet: 271 | a.MaxWithdrawAmount = e.MaxWithdrawAmount 272 | a.PolicyPeriod = e.Period 273 | a.PeriodStartTime = e.PeriodStartTime 274 | a.NextPeriodStartTime = e.NextPeriodStartTime 275 | a.FundsWithdrawnInPeriod = decimal.Zero 276 | 277 | case *BudgetRemoved: 278 | a.MaxWithdrawAmount = decimal.Zero 279 | a.PolicyPeriod = "" 280 | a.PeriodStartTime = time.Time{} 281 | a.NextPeriodStartTime = time.Time{} 282 | a.FundsWithdrawnInPeriod = decimal.Zero 283 | } 284 | 285 | return nil 286 | } 287 | 288 | type CurrentFunds struct { 289 | Amount decimal.Decimal 290 | } 291 | 292 | func (c *CurrentFunds) Evolve(event *rita.Event) error { 293 | switch e := event.Data.(type) { 294 | case *FundsDeposited: 295 | c.Amount = c.Amount.Add(e.Amount) 296 | case *FundsWithdrawn: 297 | c.Amount = c.Amount.Sub(e.Amount) 298 | } 299 | return nil 300 | } 301 | 302 | type BudgetPeriod struct { 303 | PolicyPeriod Period 304 | PolicyStartTime time.Time 305 | PolicyMaxWithdrawAmount decimal.Decimal 306 | WithdrawalsInPeriod int 307 | FundsWithdrawnInPeriod decimal.Decimal 308 | PeriodStartTime time.Time 309 | NextPeriodStartTime time.Time 310 | } 311 | 312 | func (p *BudgetPeriod) Evolve(event *rita.Event) error { 313 | switch e := event.Data.(type) { 314 | case *BudgetSet: 315 | p.PolicyPeriod = e.Period 316 | p.PolicyMaxWithdrawAmount = e.MaxWithdrawAmount 317 | p.PolicyStartTime = e.PolicyStartTime 318 | p.WithdrawalsInPeriod = 0 319 | p.FundsWithdrawnInPeriod = decimal.Zero 320 | p.PeriodStartTime, p.NextPeriodStartTime = periodWindow(e.PolicyStartTime, p.PolicyPeriod) 321 | 322 | case *BudgetRemoved: 323 | p.PolicyPeriod = "" 324 | p.PolicyMaxWithdrawAmount = decimal.Zero 325 | p.PolicyStartTime = time.Time{} 326 | p.PeriodStartTime = time.Time{} 327 | p.NextPeriodStartTime = time.Time{} 328 | 329 | case *FundsWithdrawn: 330 | if e.PeriodChanged { 331 | p.WithdrawalsInPeriod = 0 332 | p.FundsWithdrawnInPeriod = decimal.Zero 333 | p.PeriodStartTime, p.NextPeriodStartTime = periodWindow(e.Time, p.PolicyPeriod) 334 | } 335 | 336 | p.WithdrawalsInPeriod++ 337 | p.FundsWithdrawnInPeriod = p.FundsWithdrawnInPeriod.Add(e.Amount) 338 | } 339 | 340 | return nil 341 | } 342 | -------------------------------------------------------------------------------- /model_test.go: -------------------------------------------------------------------------------- 1 | //nolint 2 | package kmm 3 | 4 | import ( 5 | "encoding/json" 6 | "testing" 7 | "time" 8 | 9 | "github.com/bruth/rita" 10 | "github.com/bruth/rita/testutil" 11 | "github.com/shopspring/decimal" 12 | ) 13 | 14 | func prettyPrint(t *testing.T, v any) { 15 | b, _ := json.MarshalIndent(v, "", " ") 16 | t.Log(string(b)) 17 | } 18 | 19 | func TestPeriodWindow(t *testing.T) { 20 | is := testutil.NewIs(t) 21 | 22 | pt := time.Date(2019, time.May, 3, 12, 20, 30, 0, time.UTC) 23 | 24 | tests := map[Period]struct { 25 | StartTime time.Time 26 | NextStartTime time.Time 27 | }{ 28 | Minutely: { 29 | time.Date(2019, time.May, 3, 12, 20, 0, 0, time.UTC), 30 | time.Date(2019, time.May, 3, 12, 21, 0, 0, time.UTC), 31 | }, 32 | Daily: { 33 | time.Date(2019, time.May, 3, 0, 0, 0, 0, time.UTC), 34 | time.Date(2019, time.May, 4, 0, 0, 0, 0, time.UTC), 35 | }, 36 | Weekly: { 37 | time.Date(2019, time.April, 29, 0, 0, 0, 0, time.UTC), 38 | time.Date(2019, time.May, 6, 0, 0, 0, 0, time.UTC), 39 | }, 40 | Monthly: { 41 | time.Date(2019, time.May, 1, 0, 0, 0, 0, time.UTC), 42 | time.Date(2019, time.June, 1, 0, 0, 0, 0, time.UTC), 43 | }, 44 | } 45 | 46 | for key, test := range tests { 47 | t.Run(string(key), func(t *testing.T) { 48 | st, nst := periodWindow(pt, key) 49 | is.Equal(st, test.StartTime) 50 | is.Equal(nst, test.NextStartTime) 51 | }) 52 | } 53 | } 54 | 55 | func TestAccount(t *testing.T) { 56 | is := testutil.NewIs(t) 57 | 58 | ten, _ := decimal.NewFromString("10") 59 | twenty, _ := decimal.NewFromString("20") 60 | thirty, _ := decimal.NewFromString("30") 61 | 62 | t.Run("deposit-funds", func(t *testing.T) { 63 | clock := testutil.NewClock(time.Minute) 64 | a := Account{clock: clock} 65 | 66 | events, err := a.Decide(&rita.Command{ 67 | Data: &DepositFunds{Amount: ten}, 68 | }) 69 | is.NoErr(err) 70 | is.Equal(len(events), 1) 71 | e, ok := events[0].Data.(*FundsDeposited) 72 | is.True(ok) 73 | is.Equal(*e, FundsDeposited{Amount: ten, Time: e.Time}) 74 | 75 | // Evolve account and ensure the current funds are now 10. 76 | a.Evolve(events[0]) 77 | is.True(a.CurrentFunds.Equal(ten)) 78 | 79 | // Deposit more. 80 | events, _ = a.Decide(&rita.Command{ 81 | Data: &DepositFunds{Amount: twenty}, 82 | }) 83 | a.Evolve(events[0]) 84 | is.True(a.CurrentFunds.Equal(thirty)) 85 | }) 86 | 87 | t.Run("withdraw-funds", func(t *testing.T) { 88 | clock := testutil.NewClock(time.Minute) 89 | a := Account{clock: clock} 90 | 91 | events, err := a.Decide(&rita.Command{ 92 | Data: &WithdrawFunds{Amount: ten}, 93 | }) 94 | is.Err(err, ErrInsufficientFunds) 95 | is.Equal(len(events), 0) 96 | 97 | events, _ = a.Decide(&rita.Command{ 98 | Data: &DepositFunds{Amount: ten}, 99 | }) 100 | a.Evolve(events[0]) 101 | 102 | events, err = a.Decide(&rita.Command{ 103 | Data: &WithdrawFunds{Amount: ten}, 104 | }) 105 | is.NoErr(err) 106 | e, _ := events[0].Data.(*FundsWithdrawn) 107 | is.Equal(*e, FundsWithdrawn{Amount: ten, Time: e.Time}) 108 | 109 | a.Evolve(events[0]) 110 | is.True(a.CurrentFunds.Equal(decimal.Zero)) 111 | }) 112 | 113 | t.Run("withdraw-policy", func(t *testing.T) { 114 | clock := testutil.NewClock(time.Minute) 115 | a := Account{clock: clock} 116 | 117 | prettyPrint(t, a) 118 | 119 | events, _ := a.Decide(&rita.Command{ 120 | Data: &DepositFunds{Amount: thirty}, 121 | }) 122 | a.Evolve(events[0]) 123 | prettyPrint(t, events[0].Data) 124 | 125 | prettyPrint(t, a) 126 | 127 | events, _ = a.Decide(&rita.Command{ 128 | Data: &SetBudget{MaxAmount: ten, Period: Daily}, 129 | }) 130 | e, _ := events[0].Data.(*BudgetSet) 131 | is.Equal(*e, BudgetSet{ 132 | MaxWithdrawAmount: ten, 133 | Period: Daily, 134 | PolicyStartTime: e.PolicyStartTime, 135 | PeriodStartTime: e.PeriodStartTime, 136 | NextPeriodStartTime: e.NextPeriodStartTime, 137 | }) 138 | a.Evolve(events[0]) 139 | prettyPrint(t, events[0].Data) 140 | prettyPrint(t, a) 141 | 142 | events, err := a.Decide(&rita.Command{ 143 | Data: &WithdrawFunds{Amount: ten}, 144 | }) 145 | is.NoErr(err) 146 | 147 | a.Evolve(events[0]) 148 | prettyPrint(t, events[0].Data) 149 | prettyPrint(t, a) 150 | is.True(a.CurrentFunds.Equal(twenty)) 151 | 152 | events, err = a.Decide(&rita.Command{ 153 | Data: &WithdrawFunds{Amount: ten}, 154 | }) 155 | is.Err(err, ErrExceedWithinPeriod) 156 | 157 | // Jump to next day.. 158 | clock.Add(24 * time.Hour) 159 | 160 | events, err = a.Decide(&rita.Command{ 161 | Data: &WithdrawFunds{Amount: ten}, 162 | }) 163 | is.NoErr(err) 164 | 165 | a.Evolve(events[0]) 166 | prettyPrint(t, events[0].Data) 167 | prettyPrint(t, a) 168 | is.True(a.CurrentFunds.Equal(ten)) 169 | 170 | // Hit error again 171 | events, err = a.Decide(&rita.Command{ 172 | Data: &WithdrawFunds{Amount: ten}, 173 | }) 174 | is.Err(err, ErrExceedWithinPeriod) 175 | 176 | // Remove policy.. 177 | events, err = a.Decide(&rita.Command{ 178 | Data: &RemoveBudget{}, 179 | }) 180 | is.NoErr(err) 181 | a.Evolve(events[0]) 182 | prettyPrint(t, events[0].Data) 183 | prettyPrint(t, a) 184 | 185 | // Now can withdraw.. 186 | events, err = a.Decide(&rita.Command{ 187 | Data: &WithdrawFunds{Amount: ten}, 188 | }) 189 | is.NoErr(err) 190 | }) 191 | } 192 | 193 | func TestCurrentFunds(t *testing.T) { 194 | is := testutil.NewIs(t) 195 | 196 | var f CurrentFunds 197 | 198 | ten, _ := decimal.NewFromString("10") 199 | twenty, _ := decimal.NewFromString("20") 200 | thirty, _ := decimal.NewFromString("30") 201 | 202 | f.Evolve(&rita.Event{ 203 | Data: &FundsDeposited{ 204 | Amount: ten, 205 | }, 206 | }) 207 | 208 | f.Evolve(&rita.Event{ 209 | Data: &FundsDeposited{ 210 | Amount: thirty, 211 | }, 212 | }) 213 | 214 | f.Evolve(&rita.Event{ 215 | Data: &FundsWithdrawn{ 216 | Amount: twenty, 217 | }, 218 | }) 219 | 220 | is.Equal(f, CurrentFunds{ 221 | Amount: twenty, 222 | }) 223 | } 224 | 225 | func TestPeriodSummary(t *testing.T) { 226 | is := testutil.NewIs(t) 227 | 228 | var p BudgetPeriod 229 | 230 | ten, _ := decimal.NewFromString("10") 231 | twenty, _ := decimal.NewFromString("20") 232 | thirty, _ := decimal.NewFromString("30") 233 | 234 | pt := time.Date(2019, time.May, 3, 12, 20, 30, 0, time.UTC) 235 | st, nst := periodWindow(pt, Minutely) 236 | 237 | p.Evolve(&rita.Event{ 238 | Data: &BudgetSet{ 239 | Period: Minutely, 240 | MaxWithdrawAmount: thirty, 241 | PolicyStartTime: pt, 242 | PeriodStartTime: st, 243 | NextPeriodStartTime: nst, 244 | }, 245 | }) 246 | 247 | p.Evolve(&rita.Event{ 248 | Data: &FundsWithdrawn{ 249 | Amount: ten, 250 | Time: pt.Add(10 * time.Second), 251 | PeriodChanged: false, 252 | }, 253 | }) 254 | 255 | is.Equal(p, BudgetPeriod{ 256 | PolicyPeriod: Minutely, 257 | PolicyStartTime: pt, 258 | PolicyMaxWithdrawAmount: thirty, 259 | WithdrawalsInPeriod: 1, 260 | FundsWithdrawnInPeriod: ten, 261 | PeriodStartTime: st, 262 | NextPeriodStartTime: nst, 263 | }) 264 | 265 | p.Evolve(&rita.Event{ 266 | Data: &FundsWithdrawn{ 267 | Amount: twenty, 268 | Time: pt.Add(30 * time.Second), 269 | PeriodChanged: false, 270 | }, 271 | }) 272 | 273 | is.Equal(p, BudgetPeriod{ 274 | PolicyPeriod: Minutely, 275 | PolicyStartTime: pt, 276 | PolicyMaxWithdrawAmount: thirty, 277 | WithdrawalsInPeriod: 2, 278 | FundsWithdrawnInPeriod: thirty, 279 | PeriodStartTime: st, 280 | NextPeriodStartTime: nst, 281 | }) 282 | } 283 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package kmm 2 | 3 | import "github.com/bruth/rita/types" 4 | 5 | var ( 6 | Types = map[string]*types.Type{ 7 | // Commands and events. 8 | "deposit-funds": {Init: func() any { return &DepositFunds{} }}, 9 | "funds-deposited": {Init: func() any { return &FundsDeposited{} }}, 10 | "withdraw-funds": {Init: func() any { return &WithdrawFunds{} }}, 11 | "funds-withdrawn": {Init: func() any { return &FundsWithdrawn{} }}, 12 | "set-budget": {Init: func() any { return &SetBudget{} }}, 13 | "budget-set": {Init: func() any { return &BudgetSet{} }}, 14 | "remove-budget": {Init: func() any { return &RemoveBudget{} }}, 15 | "budget-removed": {Init: func() any { return &BudgetRemoved{} }}, 16 | // Aggregate state. 17 | "account": {Init: func() any { return NewAccount() }}, 18 | // Query results. 19 | "current-funds": {Init: func() any { return &CurrentFunds{} }}, 20 | "budget-period": {Init: func() any { return &BudgetPeriod{} }}, 21 | } 22 | ) 23 | --------------------------------------------------------------------------------