├── .github └── workflows │ └── docker.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── api ├── column.go ├── params.go ├── row_delete.go ├── row_read.go ├── row_set.go ├── server.go └── table.go ├── deploy ├── k8s.yaml └── run.yaml ├── docs ├── data_model.png └── overview.png ├── go.mod ├── go.sum ├── main.go ├── store └── gcs_bucket.go ├── tests ├── cleaner_http_test.go ├── cleaner_test.go ├── column_test.go ├── row_test.go ├── run_tests.sh └── table_test.go ├── utils ├── functions.go ├── server.go └── state.go └── worker └── cleaner.go /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker 2 | on: 3 | push: 4 | branches: 5 | - master 6 | tags: 7 | - '**' 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | 15 | - name: Set base image env 16 | run: | 17 | echo "BASE_IMAGE=ghcr.io/adrianchifor/bigbucket" >> $GITHUB_ENV 18 | 19 | - name: Set up QEMU 20 | uses: docker/setup-qemu-action@v1 21 | 22 | - name: Set up Docker buildx 23 | uses: docker/setup-buildx-action@v1 24 | 25 | - name: Login to ghcr.io 26 | uses: docker/login-action@v1 27 | with: 28 | registry: ghcr.io 29 | username: ${{ github.repository_owner }} 30 | password: ${{ secrets.CR_PAT }} 31 | 32 | - name: Build and Push latest 33 | uses: docker/build-push-action@v2 34 | with: 35 | context: . 36 | file: ./Dockerfile 37 | platforms: linux/amd64,linux/arm64 38 | tags: ${{ env.BASE_IMAGE }}:latest 39 | push: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/master' }} 40 | cache-to: type=gha,mode=max 41 | cache-from: type=gha 42 | 43 | - name: Set tagged image env 44 | if: "startsWith(github.ref, 'refs/tags/v')" 45 | run: | 46 | echo "TAGGED_IMAGE=${BASE_IMAGE}:${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV 47 | 48 | - name: Build and Push tag 49 | uses: docker/build-push-action@v2 50 | if: "startsWith(github.ref, 'refs/tags/v')" 51 | with: 52 | context: . 53 | file: ./Dockerfile 54 | platforms: linux/amd64,linux/arm64 55 | tags: ${{ env.TAGGED_IMAGE }} 56 | push: ${{ github.event_name != 'pull_request' }} 57 | cache-from: type=gha 58 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | vendor/ 15 | bin/ 16 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.19-alpine as builder 2 | 3 | RUN apk add --no-cache git gcc musl-dev 4 | 5 | WORKDIR /go/src/bigbucket 6 | COPY . /go/src/bigbucket 7 | 8 | RUN go mod download 9 | 10 | RUN go build -o /go/bin/bigbucket 11 | 12 | # Runner 13 | FROM alpine 14 | 15 | LABEL org.opencontainers.image.source https://github.com/adrianchifor/bigbucket 16 | 17 | RUN apk add --no-cache ca-certificates && update-ca-certificates 18 | 19 | COPY --from=builder /go/bin/bigbucket / 20 | 21 | # Disable debug logs in Gin http server and listen over 0.0.0.0 22 | ENV GIN_MODE release 23 | 24 | ENTRYPOINT ["/bigbucket"] 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: fmt download build test docker clean 2 | 3 | all: fmt download build 4 | 5 | fmt: 6 | go fmt 7 | 8 | download: 9 | go mod download 10 | 11 | build: 12 | go build -o bin/bigbucket 13 | 14 | test: fmt download build 15 | ifeq ($(bucket),) 16 | @echo Please pass bucket name to use for tests e.g. make test bucket=gs:// 17 | else 18 | tests/run_tests.sh $(bucket) 19 | endif 20 | 21 | docker: 22 | docker build -t bigbucket . 23 | 24 | clean: 25 | rm -rf bin/ 26 | go mod tidy 27 | go clean -modcache 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bigbucket 2 | 3 | [![Docker](https://github.com/adrianchifor/Bigbucket/workflows/Publish%20Docker/badge.svg)](https://github.com/adrianchifor/Bigbucket/actions?query=workflow%3A%22Publish+Docker%22) [![Go Report Card](https://goreportcard.com/badge/github.com/adrianchifor/Bigbucket)](https://goreportcard.com/report/github.com/adrianchifor/Bigbucket) 4 | 5 | Bigbucket is a serverless NoSQL database with a focus on scalability, availability and simplicity. It has a Bigtable-style data model with storage backed by a Cloud Storage Bucket. 6 | 7 | It's serverless in the sense of the storage layer being fully managed and the API layer being stateless and horizontally scalable, which makes it ideal to run in serverless offerings like Google Cloud Run/Functions or AWS Lambda. No servers/disks to manage, no masters/slaves, no sharding; just create a bucket and point a binary to it. 8 | 9 | The goal of the project is to offer a simple, easy to manage wide column database, with a lower barrier to entry compared to Bigtable and Cassandra, to folks who care more about scalability and availability rather than maximum performance. 10 | 11 | _Note_: The project is currently in alpha and under development. I would not recommend it for production usage just yet, but if you do try it, feedback would be highly appreciated :) 12 | 13 | Features: 14 | 15 | - Bigtable-style data model (wide column / two-dimensional KV) 16 | - Storage backed by a Cloud Storage Bucket ([GCS](https://cloud.google.com/storage/) available, S3 planned) 17 | - Fully stateless frontend with a simple RESTful API 18 | - Horizontally scalable. Need more throughput? Just add more replicas and raise Cloud Storage quotas if necessary 19 | - (WIP) Flexible data schema with the option to enforce at API layer 20 | - (WIP) Authentication and access policies per operation, per table/column 21 | - Async delete of tables and columns? Just run another instance in cleaner/garbage-collection mode 22 | - Row operations(read/set/delete) are parallelized (e.g. 1 row read ~= 1k row read) 23 | - Row cells compressed with [Zstandard](https://facebook.github.io/zstd/) 24 | - Out of the box from Cloud Storage: 25 | - Strongly consistent writes 26 | - Highly available and replicated objects 27 | - Pay per request and per GB stored /month 28 | - Object versioning and lifecycle management 29 | - Auditing 30 | - Single region for lower latency or multi-region for more availability 31 | 32 | Sections: 33 | 34 | - [Architecture and data model](#architecture-and-data-model) 35 | - [API](#api) 36 | - [Clients](#clients) 37 | - [Running](#running) 38 | - [Locally](#running-locally) 39 | - [Cloud Run](#running-in-cloud) 40 | - [Kubernetes](#running-in-kubernetes) 41 | - [Configuration](#configuration) 42 | - [Contributing](#contributing) 43 | - [TODO / Ideas](#todo--ideas) 44 | 45 | ## Architecture and data model 46 | 47 | Here's an overview diagram of how Bigbucket would look like deployed and serving requests on GCP. In this scenario: 48 | 49 | - **Bigbucket API** allows clients to interact with the wide column store through a RESTful API, like listing/counting/reading/writing/deleting rows, and listing/deleting columns and tables. It's deployed as an auto-scaling private Cloud Run service, with appropriate bucket permissions. Client requests will be load balanced between the containers and authenticated using their service account identity token ([GCP docs](https://cloud.google.com/run/docs/authenticating/developers)). 50 | 51 | - **Bigbucket Cleaner** removes tables and columns that have been marked for deletion. It's deployed as a single-container private Cloud Run service, with appropriate bucket permissions, triggered every hour by a Cloud Scheduler job. 52 | 53 | To run this yourself, check out the [Running in Cloud](#running-in-cloud) section. 54 | 55 | 56 | 57 | Also here's a visual representation of the data model and the terminology behind it. Compared to Bigtable, the current model has 2 key differences: 58 | 59 | 1. There are no column families, just columns, mainly for the sake of simplicity and because object partitioning is fully managed by the bucket. Column prefix filtering, in adition to the current specific column filtering, can be added later if there's a need for it. 60 | 61 | 2. The initial version of the API only allows fetching of the latest cell version, but there's a plan to allow listing/reading previous cell values leveraging the object versioning feature of the bucket. This allows users to have full control over the max number of versions allowed or specify an expiry/delete lifecycle, using cloud provider tools already available and understood. 62 | 63 | 64 | 65 | A few things to keep in mind when designing your schema are: 66 | 67 | - Row keys are sorted and they are the only way to filter your rows. The value of cells cannot be queried, only returned. Design your row keys with your queries in mind, with the more important values first, taking into account key prefixes as that is currently the only way to scan the table. The [Cloud Bigtable guide to choosing row keys](https://cloud.google.com/bigtable/docs/schema-design#row-keys) is a good resource here. 68 | - Reading a single row with a specified key and columns is the fastest way to get a cell value. Using row key prefixes or not specifying which columns you want will require additional requests to the bucket. 69 | - The cells are compressed with [Zstandard](https://facebook.github.io/zstd/), so no need to pre-compress yourself. 70 | - It's cheaper and faster to fetch 10 big columns rather than 100 small columns. Try to combine similarly read data together in the same column. 71 | - Write-heavy data should be kept in separate columns as there is an update limit of once per second for the same cell ([GCS quotas](https://cloud.google.com/storage/quotas#objects)). 72 | 73 | ## API 74 | 75 | _Note on naming_: Tables, columns and row keys follow [object name requirements from Google Cloud Storage](https://cloud.google.com/storage/docs/naming-objects). In short, Bigbucket API will return "HTTP 400 Bad Request" when trying to use tables, columns or row keys starting with dot "." or containing: \n, \r, \t, \b, #, [, ], *, ?, / 76 | 77 | ### Table 78 | 79 | ``` 80 | Endpoint: /api/table 81 | ``` 82 | 83 | #### Create tables 84 | 85 | Schema is flexible by default so tables are automatically created when a new row is inserted. Schema enforcement is planned for the near future. 86 | 87 | #### List tables 88 | 89 | ``` 90 | curl -X GET "http://localhost:8080/api/table" 91 | 92 | Response: 93 | { 94 | "tables": [ 95 | "test" 96 | ] 97 | } 98 | ``` 99 | 100 | #### Delete table 101 | 102 | Tables marked for deletion will need to be garbage-collected by running Bigbucket in cleaner mode. See [Running](#running) section below. 103 | 104 | ``` 105 | Querystring parameters: 106 | 107 | table (required) 108 | ``` 109 | 110 | ``` 111 | curl -X DELETE "http://localhost:8080/api/table?table=test" 112 | 113 | Response: 114 | { 115 | "success": "Table 'test' marked for deletion" 116 | } 117 | ``` 118 | 119 | ### Column 120 | 121 | ``` 122 | Endpoint: /api/column 123 | ``` 124 | 125 | #### Create columns 126 | 127 | Schema is flexible by default so columns are automatically created when rows are inserted. Schema enforcement is planned for the near future. 128 | 129 | #### List columns 130 | 131 | Because of schema flexibility, this will list the columns from only the first row in your table. 132 | 133 | ``` 134 | Querystring parameters: 135 | 136 | table (required) 137 | ``` 138 | 139 | ``` 140 | curl -X GET "http://localhost:8080/api/column?table=test" 141 | 142 | Response: 143 | { 144 | "columns": [ 145 | "col1", 146 | "col2", 147 | "col3" 148 | ], 149 | "table": "test" 150 | } 151 | ``` 152 | 153 | #### Delete column 154 | 155 | Columns marked for deletion will need to be garbage-collected by running Bigbucket in cleaner mode. See [Running](#running) section below. 156 | 157 | ``` 158 | Querystring parameters: 159 | 160 | table (required) 161 | column (required) 162 | ``` 163 | 164 | ``` 165 | curl -X DELETE "http://localhost:8080/api/column?table=test&column=col1" 166 | 167 | Response: 168 | { 169 | "success": "Column 'col1' marked for deletion in table 'test'" 170 | } 171 | ``` 172 | 173 | ### Row 174 | 175 | ``` 176 | Endpoint: /api/row 177 | ``` 178 | 179 | #### Count rows 180 | 181 | ``` 182 | Querystring parameters: 183 | 184 | table (required) 185 | 186 | prefix (optional) // Row key prefix 187 | ``` 188 | 189 | ``` 190 | curl -X GET "http://localhost:8080/api/row/count?table=test" 191 | 192 | Response: 193 | { 194 | "rowsCount": "5", 195 | "table": "test" 196 | } 197 | ``` 198 | 199 | #### List row keys 200 | 201 | ``` 202 | Querystring parameters: 203 | 204 | table (required) 205 | 206 | prefix (optional) // Row key prefix 207 | ``` 208 | 209 | ``` 210 | curl -X GET "http://localhost:8080/api/row/list?table=test" 211 | 212 | Response: 213 | { 214 | "rowKeys": ["key1", "key2", "key3", "key4", "key5"], 215 | "table": "test" 216 | } 217 | ``` 218 | 219 | #### Read rows 220 | 221 | ``` 222 | Querystring parameters: 223 | 224 | table (required) 225 | 226 | columns (optional) // Comma separated 227 | limit (optional) // Limit of rows returned 228 | 229 | Exclusive (only one of): 230 | 231 | key (required) // Row key 232 | prefix (required) // Row key prefix 233 | ``` 234 | 235 | Read single row with specified columns (fastest read op): 236 | 237 | ``` 238 | curl -X GET "http://localhost:8080/api/row?table=test&key=key1&columns=col1,col2,col3" 239 | 240 | Response: 241 | { 242 | "key1": { 243 | "col1": "val", 244 | "col2": "val", 245 | "col3": "val" 246 | } 247 | } 248 | ``` 249 | 250 | Read all rows: 251 | 252 | ``` 253 | curl -X GET "http://localhost:8080/api/row?table=test" 254 | 255 | Response: 256 | { 257 | "key1": { 258 | "col1": "val", 259 | "col2": "val", 260 | "col3": "val" 261 | }, 262 | "key2": { 263 | "col1": "val", 264 | "col2": "val", 265 | "col3": "val" 266 | }, 267 | ... 268 | } 269 | ``` 270 | 271 | Read rows with prefix and limit: 272 | 273 | ``` 274 | curl -X GET "http://localhost:8080/api/row?table=test&prefix=key&limit=1" 275 | 276 | Response: 277 | { 278 | "key1": { 279 | "col1": "val", 280 | "col2": "val", 281 | "col3": "val" 282 | } 283 | } 284 | ``` 285 | 286 | #### Set row 287 | 288 | ``` 289 | Querystring parameters: 290 | 291 | table (required) 292 | key (required) // Row key 293 | 294 | JSON Payload: 295 | 296 | { 297 | column (string): value (string), 298 | } 299 | ``` 300 | 301 | ``` 302 | curl -X POST "http://localhost:8080/api/row?table=test&key=key5" \ 303 | -d '{"col1": "newVal", "col3": "newVal"}' 304 | 305 | Response: 306 | { 307 | "success": "Set row key 'key5' in table 'test'" 308 | } 309 | ``` 310 | 311 | #### Delete rows 312 | 313 | ``` 314 | Querystring parameters: 315 | 316 | table (required) 317 | 318 | Exclusive (only one of): 319 | 320 | key (required) // Row key 321 | prefix (required) // Row key prefix 322 | ``` 323 | 324 | Delete one row: 325 | 326 | ``` 327 | curl -X DELETE "http://localhost:8080/api/row?table=test&key=key5" 328 | 329 | Response: 330 | { 331 | "success": "Row with key 'key5' was deleted from table 'test'" 332 | } 333 | ``` 334 | 335 | Delete rows with prefix: 336 | 337 | ``` 338 | curl -X DELETE "http://localhost:8080/api/row?table=test&prefix=key" 339 | 340 | Response: 341 | { 342 | "success": "4 rows with key prefix 'key' were deleted from table 'test'" 343 | } 344 | ``` 345 | 346 | ## Clients 347 | 348 | - [Python3](https://github.com/adrianchifor/bigbucket-python) 349 | - [Golang](https://github.com/adrianchifor/bigbucket-go) 350 | 351 | ## Running 352 | 353 | Create a [GCS bucket](https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-gsutil) 354 | 355 | ``` 356 | gsutil mb -p -l EUROPE-WEST1 gs:/// 357 | ``` 358 | 359 | ### Running locally 360 | 361 | #### Binary 362 | 363 | ``` 364 | git clone https://github.com/adrianchifor/Bigbucket 365 | cd Bigbucket 366 | make 367 | ``` 368 | 369 | API 370 | 371 | ``` 372 | ./bin/bigbucket --bucket gs:// 373 | ``` 374 | 375 | Cleaner 376 | 377 | ``` 378 | ./bin/bigbucket --bucket gs:// --cleaner --cleaner-interval 30 379 | ``` 380 | 381 | #### Docker 382 | 383 | API 384 | 385 | ``` 386 | docker run -d --name "bigbucket-api" \ 387 | -e BUCKET=gs:// \ 388 | -v ${HOME}/.config/gcloud:/root/.config/gcloud \ 389 | -p 8080:8080 \ 390 | ghcr.io/adrianchifor/bigbucket:latest 391 | ``` 392 | 393 | Cleaner 394 | 395 | ``` 396 | docker run -d --name "bigbucket-cleaner" \ 397 | -e BUCKET=gs:// \ 398 | -e CLEANER=true \ 399 | -e CLEANER_INTERVAL=30 \ 400 | -v ${HOME}/.config/gcloud:/root/.config/gcloud \ 401 | ghcr.io/adrianchifor/bigbucket:latest 402 | ``` 403 | 404 | We mount `${HOME}/.config/gcloud:/root/.config/gcloud` in both cases so the containers can use our local gcloud credentials to talk to the bucket. 405 | 406 | Let's test it 407 | 408 | ``` 409 | # Set a row 410 | $ curl -X POST "http://localhost:8080/api/row?table=test&key=key1" \ 411 | -d '{"foo": "hello", "bar": "world"}' | jq . 412 | 413 | { 414 | "success": "Set row key 'key1' in table 'test'" 415 | } 416 | 417 | # Get the row 418 | $ curl -X GET "http://localhost:8080/api/row?table=test&key=key1" | jq . 419 | 420 | { 421 | "key1": { 422 | "bar": "world", 423 | "foo": "hello" 424 | } 425 | } 426 | 427 | # Delete the table 428 | $ curl -X DELETE "http://localhost:8080/api/table?table=test" | jq . 429 | 430 | { 431 | "success": "Table 'test' marked for deletion" 432 | } 433 | 434 | # Check cleaner for garbage-collection 435 | $ docker logs bigbucket-cleaner 436 | 437 | 2020/05/04 19:10:34 Running cleaner... 438 | 2020/05/04 19:10:35 Running cleaner every 30 seconds... 439 | 2020/05/04 19:18:36 Table 'test' cleaned up 440 | 441 | # Stop containers 442 | $ docker kill bigbucket-api 443 | $ docker kill bigbucket-cleaner 444 | ``` 445 | 446 | ### Running in Cloud 447 | 448 | There's an example [deploy/run.yaml](./deploy/run.yaml) file on how to deploy Bigbucket to GCP, like in the first diagram in [Architecture and data model](#architecture-and-data-model), using [run-marathon](https://github.com/adrianchifor/run-marathon). 449 | 450 | Modify [deploy/run.yaml](./deploy/run.yaml) to suit your environment 451 | 452 | ``` 453 | git clone https://github.com/adrianchifor/Bigbucket 454 | cd Bigbucket/deploy 455 | vim run.yaml 456 | ``` 457 | 458 | Replace all occurances of `your_*` with your own project, region, bucket etc. 459 | 460 | Let's deploy it 461 | 462 | ``` 463 | # Install run-marathon 464 | $ pip3 install --user run-marathon 465 | 466 | $ run check 467 | Cloud Run, Build, Container Registry, PubSub and Scheduler APIs are enabled. All good! 468 | 469 | # Build and push Docker image to GCR 470 | $ run build 471 | ... 472 | 473 | # Create service accounts, attach IAM roles, deploy to Cloud Run and create Cloud Scheduler job 474 | $ run deploy 475 | ... 476 | 477 | # Get the endpoint of your API 478 | $ run ls 479 | SERVICE REGION URL LAST DEPLOYED BY LAST DEPLOYED AT 480 | ✔ bigbucket-api europe-west1 https://YOUR_API_ENDPOINT you some time 481 | ``` 482 | 483 | Let's test it 484 | 485 | ``` 486 | # Use your account identity token to authenticate to the private API endpoint 487 | $ alias gcurl='curl --header "Authorization: Bearer $(gcloud auth print-identity-token)"' 488 | 489 | # Set a row 490 | $ gcurl -X POST "https://YOUR_API_ENDPOINT/api/row?table=test&key=key1" \ 491 | -d '{"foo": "hello", "bar": "world"}' | jq . 492 | 493 | { 494 | "success": "Set row key 'key1' in table 'test'" 495 | } 496 | 497 | # Get the row 498 | $ gcurl -X GET "https://YOUR_API_ENDPOINT/api/row?table=test&key=key1" | jq . 499 | 500 | { 501 | "key1": { 502 | "bar": "world", 503 | "foo": "hello" 504 | } 505 | } 506 | ``` 507 | 508 | Nice! Now you've got load balanced, auto-scaling private Bigbucket API containers with TLS, and a Bigbucket Cleaner container triggered every hour. 509 | 510 | ### Running in Kubernetes 511 | 512 | Change the `BUCKET` environment variable in [deploy/k8s.yaml](./deploy/k8s.yaml) and run: 513 | 514 | ``` 515 | $ kubectl apply -f deploy/k8s.yaml 516 | 517 | deployment.apps/bigbucket configured 518 | service/bigbucket configured 519 | cronjob.batch/bigbucket-cleaner configured 520 | ``` 521 | 522 | This will deploy the Bigbucket API as a Deployment + Service and the Bigbucket Cleaner as an hourly CronJob. 523 | 524 | In terms of bucket access, make sure the pods have appropriate permissions to read/write/delete objects in the bucket. If you run on GKE it's recommended that you make use of [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity). 525 | 526 | ## Configuration 527 | 528 | ### Flags 529 | 530 | ``` 531 | $ ./bin/bigbucket --help 532 | Usage of ./bin/bigbucket: 533 | -bucket string 534 | Bucket name (required, e.g. gs://) 535 | -cleaner 536 | Run Bigbucket in cleaner mode (default false). Will garbage collect tables and columns marked for deletion. Executes based on --cleaner-interval 537 | -cleaner-http 538 | Run Bigbucket in cleaner HTTP mode (default false). Executes on HTTP POST to /; to be used with https://cloud.google.com/scheduler/docs/creating 539 | -cleaner-interval int 540 | Bigbucket cleaner interval (default 0, runs only once). To run cleaner every hour, you can set --cleaner-interval 3600 541 | -port int 542 | Server port (default 8080) 543 | -version 544 | Version 545 | ``` 546 | 547 | ### Environment variables 548 | 549 | If the flags are not set, Bigbucket will look for the equivalent env vars: 550 | 551 | ``` 552 | --bucket -> BUCKET 553 | --cleaner -> CLEANER 554 | --cleaner-http -> CLEANER_HTTP 555 | --cleaner-interval -> CLEANER_INTERVAL 556 | --port -> PORT 557 | ``` 558 | 559 | ## Contributing 560 | 561 | Requirements: Go 1.16, gcloud/gsutil setup (for GCS usage) 562 | 563 | ### Project structure 564 | 565 | ``` 566 | api/ 567 | column* - listing/deleting columns 568 | table* - listing/deleting tables 569 | row* - counting/listing/reading/writing/deleting rows 570 | params.go - HTTP parameter handling and validation 571 | server.go - HTTP server and router 572 | 573 | store/ 574 | gcs* - interact with Google Cloud Storage buckets and objects 575 | 576 | tests/ 577 | cleaner* - tests for cleaner/garbage-collection functionality 578 | column* - tests for column ops 579 | row* - tests for row ops 580 | table* - tests for table ops 581 | run_tests.sh - helper script to prepare env and run tests suite 582 | 583 | utils/ 584 | functions.go - generic utility funcs 585 | server.go - HTTP server contructor and handlers (used in api and worker) 586 | state.go - funcs to manage deleted tables/columns state 587 | 588 | worker/ 589 | cleaner.go - runner (periodic/HTTP) and funcs for cleaning/GC of deleted tables/columns 590 | 591 | go.mod - Go version and dependencies 592 | main.go - entrypoint, handles flags/envs, bucket init and running the API or Cleaner 593 | ``` 594 | 595 | ### Building and running 596 | 597 | ``` 598 | $ make 599 | go fmt 600 | go mod download 601 | go build -o bin/bigbucket 602 | 603 | $ ./bin/bigbucket --bucket gs:// 604 | [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. 605 | 606 | [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. 607 | - using env: export GIN_MODE=release 608 | - using code: gin.SetMode(gin.ReleaseMode) 609 | 610 | [GIN-debug] GET /api/table --> github.com/adrianchifor/Bigbucket/api.listTables (3 handlers) 611 | [GIN-debug] DELETE /api/table --> github.com/adrianchifor/Bigbucket/api.deleteTable (3 handlers) 612 | [GIN-debug] GET /api/column --> github.com/adrianchifor/Bigbucket/api.listColumns (3 handlers) 613 | [GIN-debug] DELETE /api/column --> github.com/adrianchifor/Bigbucket/api.deleteColumn (3 handlers) 614 | [GIN-debug] GET /api/row --> github.com/adrianchifor/Bigbucket/api.getRows (3 handlers) 615 | [GIN-debug] GET /api/row/count --> github.com/adrianchifor/Bigbucket/api.getRowsCount (3 handlers) 616 | [GIN-debug] GET /api/row/list --> github.com/adrianchifor/Bigbucket/api.listRows (3 handlers) 617 | [GIN-debug] POST /api/row --> github.com/adrianchifor/Bigbucket/api.setRow (3 handlers) 618 | [GIN-debug] DELETE /api/row --> github.com/adrianchifor/Bigbucket/api.deleteRows (3 handlers) 619 | [GIN-debug] GET /health --> github.com/adrianchifor/Bigbucket/api.RunServer.func1 (3 handlers) 620 | 2020/06/01 22:49:00 HTTP server is ready to handle requests at 127.0.0.1:8080 621 | ``` 622 | 623 | ### Tests 624 | 625 | Setup an empty bucket in GCS for testing. Make sure gcloud/gsutil is setup/authenticated locally. 626 | 627 | ``` 628 | gcloud auth application-default login 629 | ``` 630 | 631 | Running the tests suite: 632 | 633 | ``` 634 | $ make test bucket=gs:// 635 | go fmt 636 | go mod download 637 | go build -o bin/bigbucket 638 | tests/run_tests.sh gs:// 639 | 640 | Running bigbucket server 641 | 642 | Running row tests 643 | ok command-line-arguments 2.158s 644 | 645 | Running column tests 646 | ok command-line-arguments 0.212s 647 | 648 | Running table tests 649 | ok command-line-arguments 0.093s 650 | 651 | Running bigbucket cleaner 652 | 653 | Running bigbucket cleaner tests 654 | ok command-line-arguments 6.447s 655 | 656 | Killing bigbucket cleaner 657 | 658 | Running bigbucket cleaner as HTTP server 659 | 660 | Running HTTP cleaner tests 661 | ok command-line-arguments 0.587s 662 | 663 | Cleaning up test bucket 664 | Cleaning up bigbucket processes 665 | Done 666 | ``` 667 | 668 | ## TODO / Ideas 669 | 670 | - Schema enforcement at API layer 671 | - Authentication and access policies 672 | - Multiple cell versions (via bucket object versions) 673 | - Support file/blob uploads as cell values 674 | - OpenAPI file for automatic client generation 675 | - Caching at API layer of "GET api/row" request->results pairs (maybe with max memory and/or time) 676 | - Start/End/Regex row key scanning (in addition to Prefix) 677 | - Prometheus metrics 678 | - AWS S3 backend 679 | - Row key/column object triggers (for Pub/Sub). Might be useful for ETL, work queues 680 | -------------------------------------------------------------------------------- /api/column.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "sort" 7 | "strings" 8 | 9 | "github.com/adrianchifor/Bigbucket/store" 10 | "github.com/adrianchifor/Bigbucket/utils" 11 | "github.com/gin-gonic/gin" 12 | ) 13 | 14 | func listColumns(c *gin.Context) { 15 | params, err := parseRequiredRequestParams(c, "table") 16 | if err != nil { 17 | return 18 | } 19 | 20 | tables, _, err := getTables() 21 | if err != nil { 22 | log.Print(err) 23 | c.JSON(500, gin.H{ 24 | "error": "Internal error, check server logs", 25 | }) 26 | return 27 | } 28 | if utils.Search(tables, params["table"]) == -1 { 29 | c.JSON(404, gin.H{ 30 | "error": fmt.Sprintf("Table '%s' not found or marked for deletion", params["table"]), 31 | }) 32 | return 33 | } 34 | 35 | columns, _, err := getColumns(params["table"]) 36 | if err != nil { 37 | log.Print(err) 38 | c.JSON(500, gin.H{ 39 | "error": "Internal error, check server logs", 40 | }) 41 | return 42 | } 43 | 44 | c.JSON(200, gin.H{"table": params["table"], "columns": columns}) 45 | } 46 | 47 | func deleteColumn(c *gin.Context) { 48 | params, err := parseRequiredRequestParams(c, "table", "column") 49 | if err != nil { 50 | return 51 | } 52 | 53 | tables, _, err := getTables() 54 | if err != nil { 55 | log.Print(err) 56 | c.JSON(500, gin.H{ 57 | "error": "Internal error, check server logs", 58 | }) 59 | return 60 | } 61 | if utils.Search(tables, params["table"]) == -1 { 62 | c.JSON(404, gin.H{ 63 | "error": fmt.Sprintf("Table '%s' not found or marked for deletion", params["table"]), 64 | }) 65 | return 66 | } 67 | 68 | columns, columnsToDelete, err := getColumns(params["table"]) 69 | if err != nil { 70 | log.Print(err) 71 | c.JSON(500, gin.H{ 72 | "error": "Internal error, check server logs", 73 | }) 74 | return 75 | } 76 | 77 | if utils.Search(columns, params["column"]) == -1 { 78 | c.JSON(404, gin.H{ 79 | "error": fmt.Sprintf("Column '%s' not found or marked for deletion in table '%s'", params["column"], params["table"]), 80 | }) 81 | } else { 82 | columnsToDelete = append(columnsToDelete, params["column"]) 83 | err = utils.WriteState(fmt.Sprintf("bigbucket/%s/.delete_columns", params["table"]), columnsToDelete) 84 | if err != nil { 85 | log.Print(err) 86 | c.JSON(500, gin.H{ 87 | "error": "Internal error, check server logs", 88 | }) 89 | return 90 | } 91 | c.JSON(200, gin.H{ 92 | "success": fmt.Sprintf("Column '%s' marked for deletion in table '%s'", params["column"], params["table"]), 93 | }) 94 | } 95 | } 96 | 97 | func getColumns(table string) (columns []string, columnsToDelete []string, err error) { 98 | columns = []string{} 99 | objects, err := store.ListObjects(fmt.Sprintf("bigbucket/%s/", table), "", 2) 100 | if err != nil { 101 | return nil, nil, err 102 | } 103 | if len(objects) < 2 { 104 | return columns, nil, nil 105 | } 106 | indexDelete := utils.Search(objects, fmt.Sprintf("bigbucket/%s/.delete_columns", table)) 107 | if indexDelete > -1 { 108 | objects = utils.RemoveIndex(objects, indexDelete) 109 | } 110 | 111 | firstKey := strings.Split(objects[0], "/")[2] 112 | firstKeyPath := fmt.Sprintf("bigbucket/%s/%s/", table, firstKey) 113 | objects, err = store.ListObjects(firstKeyPath, "", 0) 114 | if err != nil { 115 | return nil, nil, err 116 | } 117 | 118 | for _, column := range objects { 119 | cleanColumn := strings.Replace(column, firstKeyPath, "", 1) 120 | if cleanColumn != "" { 121 | columns = append(columns, cleanColumn) 122 | } 123 | } 124 | 125 | // Remove columns marked for deletion from results 126 | columnsToDelete = utils.GetState(fmt.Sprintf("bigbucket/%s/.delete_columns", table)) 127 | for _, columnToDelete := range columnsToDelete { 128 | index := utils.Search(columns, columnToDelete) 129 | if index > -1 { 130 | columns = utils.RemoveIndex(columns, index) 131 | } 132 | } 133 | 134 | sort.Strings(columns) 135 | return columns, columnsToDelete, nil 136 | } 137 | -------------------------------------------------------------------------------- /api/params.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | var ( 12 | invalidChars = []string{"\n", "\r", "\t", "\b", "#", "[", "]", "*", "?", "/"} 13 | ) 14 | 15 | func parseRequiredRequestParams(c *gin.Context, params ...string) (map[string]string, error) { 16 | parsedParams := make(map[string]string) 17 | for _, param := range params { 18 | paramValue := strings.TrimSpace(c.Query(param)) 19 | if paramValue == "" { 20 | c.JSON(400, gin.H{ 21 | "error": fmt.Sprintf("Please provide '%s' as a querystring parameter", param), 22 | }) 23 | return nil, fmt.Errorf("Failed to parse '%s' querystring parameter", param) 24 | } 25 | if err := validateParam(c, paramValue); err != nil { 26 | return nil, err 27 | } 28 | 29 | parsedParams[param] = paramValue 30 | } 31 | 32 | return parsedParams, nil 33 | } 34 | 35 | func parseOptionalRequestParams(c *gin.Context, params ...string) (map[string]string, error) { 36 | parsedParams := make(map[string]string) 37 | for _, param := range params { 38 | paramValue := strings.TrimSpace(c.Query(param)) 39 | if err := validateParam(c, paramValue); err != nil { 40 | return nil, err 41 | } 42 | 43 | parsedParams[param] = paramValue 44 | } 45 | 46 | return parsedParams, nil 47 | } 48 | 49 | func parseExclusiveRequestParams(c *gin.Context, firstParam string, secondParam string) (string, string, error) { 50 | firstParamVal := strings.TrimSpace(c.Query(firstParam)) 51 | secondParamVal := strings.TrimSpace(c.Query(secondParam)) 52 | 53 | if firstParamVal != "" && secondParamVal != "" { 54 | c.JSON(400, gin.H{ 55 | "error": fmt.Sprintf("Please provide only one of '%s' or '%s' as a querystring parameter", firstParam, secondParam), 56 | }) 57 | return "", "", fmt.Errorf("Failed to parse '%s, %s' querystring parameters", firstParam, secondParam) 58 | } 59 | if err := validateParam(c, firstParamVal); err != nil { 60 | return "", "", err 61 | } 62 | if err := validateParam(c, secondParamVal); err != nil { 63 | return "", "", err 64 | } 65 | 66 | return firstParamVal, secondParamVal, nil 67 | } 68 | 69 | func validateParam(c *gin.Context, paramValue string) error { 70 | if !isObjectNameValid(paramValue) { 71 | c.JSON(400, gin.H{ 72 | "error": fmt.Sprintf("Parameters cannot start with '.' nor contain the following characters: %s", invalidChars), 73 | }) 74 | return errors.New("Failed to validate querystring parameter") 75 | } 76 | return nil 77 | } 78 | 79 | func isObjectNameValid(object string) bool { 80 | if strings.HasPrefix(object, ".") { 81 | return false 82 | } 83 | 84 | for _, char := range invalidChars { 85 | if strings.Contains(object, char) { 86 | return false 87 | } 88 | } 89 | 90 | return true 91 | } 92 | 93 | func allowCORSForBrowsers(c *gin.Context) { 94 | if value := c.Request.Header.Get("User-Agent"); strings.HasPrefix(value, "Mozilla") { 95 | c.Writer.Header().Add("Access-Control-Allow-Origin", "*") 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /api/row_delete.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | "sync" 8 | 9 | "github.com/adrianchifor/Bigbucket/store" 10 | "github.com/adrianchifor/Bigbucket/utils" 11 | "github.com/adrianchifor/go-parallel" 12 | "github.com/gin-gonic/gin" 13 | ) 14 | 15 | func deleteRows(c *gin.Context) { 16 | params, err := parseRequiredRequestParams(c, "table") 17 | if err != nil { 18 | return 19 | } 20 | rowKey, rowPrefix, err := parseExclusiveRequestParams(c, "key", "prefix") 21 | if err != nil { 22 | return 23 | } 24 | if rowKey == "" && rowPrefix == "" { 25 | c.JSON(400, gin.H{ 26 | "error": "Please provide one of 'key' or 'prefix' as a querystring parameter. " + 27 | "To delete the table use DELETE /api/table?table=", 28 | }) 29 | return 30 | } 31 | 32 | keyPath := fmt.Sprintf("bigbucket/%s/%s/", params["table"], rowKey) 33 | if rowPrefix != "" { 34 | keyPath = fmt.Sprintf("bigbucket/%s/%s", params["table"], rowPrefix) 35 | } 36 | 37 | objects, err := store.ListObjects(keyPath, "", 0) 38 | if err != nil { 39 | log.Print(err) 40 | c.JSON(500, gin.H{ 41 | "error": "Internal error, check server logs", 42 | }) 43 | return 44 | } 45 | if len(objects) == 0 { 46 | errMsg := fmt.Sprintf("Row key '%s' not found in table '%s'", rowKey, params["table"]) 47 | if rowPrefix != "" { 48 | errMsg = fmt.Sprintf("Rows with key prefix '%s' not found in table '%s'", rowPrefix, params["table"]) 49 | } 50 | c.JSON(404, gin.H{ 51 | "error": errMsg, 52 | }) 53 | return 54 | } 55 | 56 | deleteJobPool := parallel.CustomJobPool(parallel.JobPoolConfig{ 57 | WorkerCount: len(objects), 58 | JobQueueSize: len(objects) * 10, 59 | }) 60 | defer deleteJobPool.Close() 61 | 62 | deletesFailed := map[string]error{} 63 | deletesFailedMutex := &sync.Mutex{} 64 | 65 | for _, object := range objects { 66 | object := object 67 | deleteJobPool.AddJob(func() { 68 | err := store.DeleteObject(object) 69 | if err != nil { 70 | objectSplit := strings.Split(object, "/") 71 | failedKey := objectSplit[2] 72 | failedColumn := objectSplit[3] 73 | 74 | deletesFailedMutex.Lock() 75 | defer deletesFailedMutex.Unlock() 76 | 77 | deletesFailed[fmt.Sprintf("%s/%s", failedKey, failedColumn)] = err 78 | } 79 | }) 80 | } 81 | 82 | err = deleteJobPool.Wait() 83 | if err != nil { 84 | log.Print(err) 85 | c.JSON(500, gin.H{ 86 | "error": "Internal error, check server logs", 87 | }) 88 | return 89 | } 90 | if len(deletesFailed) > 0 { 91 | keyColumnsFailed := []string{} 92 | bucketRateLimit := false 93 | for keyColumn, deleteErr := range deletesFailed { 94 | log.Print(deleteErr) 95 | if !bucketRateLimit && strings.Contains(deleteErr.Error(), "429") { 96 | bucketRateLimit = true 97 | } 98 | keyColumnsFailed = append(keyColumnsFailed, keyColumn) 99 | } 100 | 101 | errorMsg := fmt.Sprintf("Check server logs, some columns failed to be deleted: %s", keyColumnsFailed) 102 | if bucketRateLimit { 103 | errorMsg = fmt.Sprintf("Bucket is rate limiting, some columns failed to be deleted: %s", keyColumnsFailed) 104 | } 105 | c.JSON(500, gin.H{ 106 | "error": errorMsg, 107 | }) 108 | return 109 | } 110 | 111 | successMsg := fmt.Sprintf("Row with key '%s' was deleted from table '%s'", rowKey, params["table"]) 112 | if rowPrefix != "" { 113 | rowsFound := []string{} 114 | for _, object := range objects { 115 | objectKey := strings.Split(object, "/")[2] 116 | if utils.Search(rowsFound, objectKey) == -1 { 117 | rowsFound = append(rowsFound, objectKey) 118 | } 119 | } 120 | successMsg = fmt.Sprintf("%d rows with key prefix '%s' were deleted from table '%s'", len(rowsFound), rowPrefix, params["table"]) 121 | } 122 | c.JSON(200, gin.H{ 123 | "success": successMsg, 124 | }) 125 | } 126 | -------------------------------------------------------------------------------- /api/row_read.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "sort" 7 | "strconv" 8 | "strings" 9 | "sync" 10 | 11 | "github.com/adrianchifor/Bigbucket/store" 12 | "github.com/adrianchifor/Bigbucket/utils" 13 | "github.com/adrianchifor/go-parallel" 14 | "github.com/gin-gonic/gin" 15 | ) 16 | 17 | func getRows(c *gin.Context) { 18 | allowCORSForBrowsers(c) 19 | tableMap, err := parseRequiredRequestParams(c, "table") 20 | if err != nil { 21 | return 22 | } 23 | rowKey, rowPrefix, err := parseExclusiveRequestParams(c, "key", "prefix") 24 | if err != nil { 25 | return 26 | } 27 | columnsCountMap, err := parseOptionalRequestParams(c, "columns", "limit") 28 | if err != nil { 29 | return 30 | } 31 | params := utils.MergeMaps(tableMap, columnsCountMap) 32 | 33 | columnsList := []string{} 34 | if params["columns"] != "" { 35 | columnsList = strings.Split(params["columns"], ",") 36 | } 37 | 38 | results := make(map[string]map[string]string) 39 | 40 | // When a specific key and columns are requested (no queries, direct fetches) 41 | if rowKey != "" && len(columnsList) > 0 { 42 | var err error 43 | results[rowKey], err = getRowColumns(params["table"], rowKey, columnsList) 44 | if err != nil { 45 | log.Print(err) 46 | c.JSON(500, gin.H{ 47 | "error": "Internal error, check server logs", 48 | }) 49 | return 50 | } 51 | c.JSON(200, results) 52 | return 53 | } 54 | 55 | rowsLimitInt := 0 56 | if params["limit"] != "" { 57 | if n, err := strconv.Atoi(params["limit"]); err == nil { 58 | rowsLimitInt = n 59 | } else { 60 | c.JSON(400, gin.H{"error": "'limit' parameter has to be an integer"}) 61 | return 62 | } 63 | } 64 | 65 | keyPath := fmt.Sprintf("bigbucket/%s/", params["table"]) 66 | if rowKey != "" { 67 | keyPath = fmt.Sprintf("bigbucket/%s/%s/", params["table"], rowKey) 68 | } else if rowPrefix != "" { 69 | keyPath = fmt.Sprintf("bigbucket/%s/%s", params["table"], rowPrefix) 70 | } 71 | 72 | objects, err := store.ListObjects(keyPath, "", 0) 73 | if err != nil { 74 | log.Print(err) 75 | c.JSON(500, gin.H{ 76 | "error": "Internal error, check server logs", 77 | }) 78 | return 79 | } 80 | if len(objects) == 0 { 81 | errMsg := fmt.Sprintf("Table '%s' not found", params["table"]) 82 | if rowKey != "" { 83 | errMsg = fmt.Sprintf("Row key '%s' not found in table '%s'", rowKey, params["table"]) 84 | } else if rowPrefix != "" { 85 | errMsg = fmt.Sprintf("Rows with key prefix '%s' not found in table '%s'", rowPrefix, params["table"]) 86 | } 87 | c.JSON(404, gin.H{ 88 | "error": errMsg, 89 | }) 90 | return 91 | } 92 | 93 | rowsJobPool := parallel.CustomJobPool(parallel.JobPoolConfig{ 94 | WorkerCount: len(objects), 95 | JobQueueSize: len(objects) * 10, 96 | }) 97 | defer rowsJobPool.Close() 98 | 99 | rowsAdded := 0 100 | resultsMutex := &sync.Mutex{} 101 | 102 | sort.Strings(objects) 103 | for _, object := range objects { 104 | object := object 105 | if strings.HasSuffix(object, "/") || strings.Count(object, "/") < 3 { 106 | // Skip if object is not column 107 | continue 108 | } 109 | objectSplit := strings.Split(object, "/") 110 | objectKey := objectSplit[2] 111 | objectColumn := objectSplit[3] 112 | if len(columnsList) > 0 && utils.Search(columnsList, objectColumn) == -1 { 113 | // Skip if current column is not in specified columns 114 | continue 115 | } 116 | 117 | resultsMutex.Lock() 118 | if _, exists := results[objectKey]; !exists { 119 | if rowsLimitInt > 0 { 120 | if rowsAdded == rowsLimitInt { 121 | // Break loop if max row limit is reached 122 | resultsMutex.Unlock() 123 | break 124 | } 125 | rowsAdded++ 126 | } 127 | results[objectKey] = make(map[string]string) 128 | } 129 | resultsMutex.Unlock() 130 | 131 | rowsJobPool.AddJob(func() { 132 | columnValue, err := store.ReadObject(object) 133 | if err != nil { 134 | log.Print(err, fmt.Sprintf(" (%s)", object)) 135 | return 136 | } 137 | resultsMutex.Lock() 138 | defer resultsMutex.Unlock() 139 | results[objectKey][objectColumn] = string(columnValue) 140 | }) 141 | } 142 | 143 | err = rowsJobPool.Wait() 144 | if err != nil { 145 | log.Print(err) 146 | c.JSON(500, gin.H{ 147 | "error": "Internal error, check server logs", 148 | }) 149 | return 150 | } 151 | 152 | c.JSON(200, results) 153 | } 154 | 155 | func getRowColumns(table string, rowKey string, columns []string) (map[string]string, error) { 156 | results := make(map[string]string) 157 | resultsMutex := &sync.Mutex{} 158 | 159 | columnsJobPool := parallel.CustomJobPool(parallel.JobPoolConfig{ 160 | WorkerCount: len(columns), 161 | JobQueueSize: len(columns) * 10, 162 | }) 163 | defer columnsJobPool.Close() 164 | 165 | for _, column := range columns { 166 | column := column 167 | columnsJobPool.AddJob(func() { 168 | columnPath := fmt.Sprintf("bigbucket/%s/%s/%s", table, rowKey, column) 169 | columnValue, err := store.ReadObject(columnPath) 170 | if err != nil { 171 | log.Print(err, fmt.Sprintf(" (%s)", columnPath)) 172 | return 173 | } 174 | resultsMutex.Lock() 175 | defer resultsMutex.Unlock() 176 | results[column] = string(columnValue) 177 | }) 178 | } 179 | 180 | err := columnsJobPool.Wait() 181 | if err != nil { 182 | return nil, err 183 | } 184 | 185 | return results, nil 186 | } 187 | 188 | func getRowsCount(c *gin.Context) { 189 | rows, table, err := listRowKeys(c) 190 | if err != nil { 191 | return 192 | } 193 | 194 | c.JSON(200, gin.H{"table": table, "rowsCount": strconv.Itoa(len(rows))}) 195 | } 196 | 197 | func listRows(c *gin.Context) { 198 | rows, table, err := listRowKeys(c) 199 | if err != nil { 200 | return 201 | } 202 | 203 | rowKeys := []string{} 204 | for _, row := range rows { 205 | rowKey := strings.Split(row, "/")[2] 206 | rowKeys = append(rowKeys, rowKey) 207 | } 208 | sort.Strings(rowKeys) 209 | 210 | c.JSON(200, gin.H{"table": table, "rowKeys": rowKeys}) 211 | } 212 | 213 | func listRowKeys(c *gin.Context) ([]string, string, error) { 214 | tableMap, err := parseRequiredRequestParams(c, "table") 215 | if err != nil { 216 | return nil, "", err 217 | } 218 | prefixMap, err := parseOptionalRequestParams(c, "prefix") 219 | if err != nil { 220 | return nil, "", err 221 | } 222 | params := utils.MergeMaps(tableMap, prefixMap) 223 | 224 | keysPath := fmt.Sprintf("bigbucket/%s/", params["table"]) 225 | if params["prefix"] != "" { 226 | keysPath = fmt.Sprintf("bigbucket/%s/%s", params["table"], params["prefix"]) 227 | } 228 | 229 | rows, err := store.ListObjects(keysPath, "/", 0) 230 | if err != nil { 231 | log.Print(err) 232 | c.JSON(500, gin.H{ 233 | "error": "Internal error, check server logs", 234 | }) 235 | return nil, "", err 236 | } 237 | 238 | return rows, params["table"], nil 239 | } 240 | -------------------------------------------------------------------------------- /api/row_set.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | "sync" 8 | 9 | "github.com/adrianchifor/Bigbucket/store" 10 | "github.com/adrianchifor/go-parallel" 11 | "github.com/gin-gonic/gin" 12 | ) 13 | 14 | func setRow(c *gin.Context) { 15 | params, err := parseRequiredRequestParams(c, "table", "key") 16 | if err != nil { 17 | return 18 | } 19 | 20 | var jsonPayload map[string]string 21 | if err := c.BindJSON(&jsonPayload); err != nil { 22 | c.JSON(400, gin.H{ 23 | "error": "Could not parse JSON payload, needs to follow { column string: value string }", 24 | }) 25 | return 26 | } 27 | if len(jsonPayload) == 0 { 28 | c.JSON(400, gin.H{ 29 | "error": "Nothing to set, JSON payload is empty. Needs to follow { column string: value string }", 30 | }) 31 | return 32 | } 33 | 34 | cleanedJsonPayload := make(map[string]string) 35 | for column, value := range jsonPayload { 36 | column := strings.TrimSpace(column) 37 | if column == "" { 38 | c.JSON(400, gin.H{ 39 | "error": "Columns cannot be empty", 40 | }) 41 | return 42 | } 43 | if !isObjectNameValid(column) { 44 | c.JSON(400, gin.H{ 45 | "error": fmt.Sprintf("Columns cannot start with '.' nor contain the following characters: %s", invalidChars), 46 | }) 47 | return 48 | } 49 | 50 | cleanedJsonPayload[column] = value 51 | } 52 | 53 | columnsJobPool := parallel.CustomJobPool(parallel.JobPoolConfig{ 54 | WorkerCount: len(cleanedJsonPayload), 55 | JobQueueSize: len(cleanedJsonPayload) * 10, 56 | }) 57 | defer columnsJobPool.Close() 58 | 59 | writesFailed := map[string]error{} 60 | writesFailedMutex := &sync.Mutex{} 61 | 62 | for column, value := range cleanedJsonPayload { 63 | column := column 64 | value := value 65 | columnsJobPool.AddJob(func() { 66 | err := store.WriteObject(fmt.Sprintf("bigbucket/%s/%s/%s", params["table"], params["key"], column), []byte(value)) 67 | if err != nil { 68 | writesFailedMutex.Lock() 69 | defer writesFailedMutex.Unlock() 70 | 71 | writesFailed[column] = err 72 | } 73 | }) 74 | } 75 | 76 | err = columnsJobPool.Wait() 77 | if err != nil { 78 | log.Print(err) 79 | c.JSON(500, gin.H{ 80 | "error": "Internal error, check server logs", 81 | }) 82 | return 83 | } 84 | if len(writesFailed) > 0 { 85 | columnsFailed := []string{} 86 | bucketRateLimit := false 87 | for column, writeErr := range writesFailed { 88 | log.Print(writeErr) 89 | if !bucketRateLimit && strings.Contains(writeErr.Error(), "429") { 90 | bucketRateLimit = true 91 | } 92 | columnsFailed = append(columnsFailed, column) 93 | } 94 | 95 | errorMsg := fmt.Sprintf("Check server logs, some columns failed to persist: %s", columnsFailed) 96 | if bucketRateLimit { 97 | errorMsg = fmt.Sprintf("Bucket is rate limiting, some columns failed to persist: %s", columnsFailed) 98 | } 99 | c.JSON(500, gin.H{ 100 | "error": errorMsg, 101 | }) 102 | return 103 | } 104 | 105 | c.JSON(200, gin.H{ 106 | "success": fmt.Sprintf("Set row key '%s' in table '%s'", params["key"], params["table"]), 107 | }) 108 | } 109 | -------------------------------------------------------------------------------- /api/server.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "github.com/adrianchifor/Bigbucket/utils" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | // RunServer runs the HTTP server+router for API 9 | func RunServer(port int) { 10 | router := gin.Default() 11 | 12 | apiRoute := router.Group("/api") 13 | { 14 | apiRoute.GET("/table", listTables) 15 | apiRoute.DELETE("/table", deleteTable) 16 | 17 | apiRoute.GET("/column", listColumns) 18 | apiRoute.DELETE("/column", deleteColumn) 19 | 20 | apiRoute.GET("/row", getRows) 21 | apiRoute.GET("/row/count", getRowsCount) 22 | apiRoute.GET("/row/list", listRows) 23 | apiRoute.POST("/row", setRow) 24 | apiRoute.DELETE("/row", deleteRows) 25 | } 26 | router.GET("/health", func(c *gin.Context) { 27 | c.String(200, "UP") 28 | }) 29 | 30 | utils.RunServer(port, router) 31 | } 32 | -------------------------------------------------------------------------------- /api/table.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "sort" 7 | 8 | "github.com/adrianchifor/Bigbucket/store" 9 | "github.com/adrianchifor/Bigbucket/utils" 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | func listTables(c *gin.Context) { 14 | tables, _, err := getTables() 15 | if err != nil { 16 | log.Print(err) 17 | c.JSON(500, gin.H{ 18 | "error": "Internal error, check server logs", 19 | }) 20 | return 21 | } 22 | 23 | c.JSON(200, gin.H{"tables": tables}) 24 | } 25 | 26 | func deleteTable(c *gin.Context) { 27 | params, err := parseRequiredRequestParams(c, "table") 28 | if err != nil { 29 | return 30 | } 31 | 32 | tables, tablesToDelete, err := getTables() 33 | if err != nil { 34 | log.Print(err) 35 | c.JSON(500, gin.H{ 36 | "error": "Internal error, check server logs", 37 | }) 38 | return 39 | } 40 | 41 | if utils.Search(tables, params["table"]) == -1 { 42 | c.JSON(404, gin.H{ 43 | "error": fmt.Sprintf("Table '%s' not found or marked for deletion", params["table"]), 44 | }) 45 | } else { 46 | tablesToDelete = append(tablesToDelete, params["table"]) 47 | err = utils.WriteState("bigbucket/.delete_tables", tablesToDelete) 48 | if err != nil { 49 | log.Print(err) 50 | c.JSON(500, gin.H{ 51 | "error": "Internal error, check server logs", 52 | }) 53 | return 54 | } 55 | c.JSON(200, gin.H{ 56 | "success": fmt.Sprintf("Table '%s' marked for deletion", params["table"]), 57 | }) 58 | } 59 | } 60 | 61 | func getTables() (tables []string, tablesToDelete []string, err error) { 62 | objects, err := store.ListObjects("bigbucket/", "/", 0) 63 | if err != nil { 64 | return nil, nil, err 65 | } 66 | tables = utils.CleanupTables(objects) 67 | 68 | // Remove tables marked for deletion from results 69 | tablesToDelete = utils.GetState("bigbucket/.delete_tables") 70 | for _, tableToDelete := range tablesToDelete { 71 | index := utils.Search(tables, tableToDelete) 72 | if index > -1 { 73 | tables = utils.RemoveIndex(tables, index) 74 | } 75 | } 76 | 77 | sort.Strings(tables) 78 | return tables, tablesToDelete, nil 79 | } 80 | -------------------------------------------------------------------------------- /deploy/k8s.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: bigbucket 6 | labels: 7 | app: bigbucket 8 | spec: 9 | replicas: 1 10 | revisionHistoryLimit: 5 11 | selector: 12 | matchLabels: 13 | app: bigbucket 14 | template: 15 | metadata: 16 | labels: 17 | app: bigbucket 18 | spec: 19 | containers: 20 | - name: bigbucket 21 | image: ghcr.io/adrianchifor/bigbucket:latest 22 | imagePullPolicy: Always 23 | env: 24 | - name: BUCKET 25 | value: gs://your-bucket 26 | resources: 27 | requests: 28 | cpu: 50m 29 | memory: 128Mi 30 | ports: 31 | - containerPort: 8080 32 | livenessProbe: 33 | tcpSocket: 34 | port: 8080 35 | initialDelaySeconds: 3 36 | readinessProbe: 37 | httpGet: 38 | path: /health 39 | port: 8080 40 | initialDelaySeconds: 5 41 | periodSeconds: 30 42 | --- 43 | apiVersion: v1 44 | kind: Service 45 | metadata: 46 | name: bigbucket 47 | spec: 48 | selector: 49 | app: bigbucket 50 | ports: 51 | - protocol: TCP 52 | port: 8080 53 | targetPort: 8080 54 | --- 55 | apiVersion: batch/v1beta1 56 | kind: CronJob 57 | metadata: 58 | name: bigbucket-cleaner 59 | labels: 60 | app: bigbucket-cleaner 61 | spec: 62 | schedule: "0 * * * *" 63 | concurrencyPolicy: "Forbid" 64 | successfulJobsHistoryLimit: 2 65 | startingDeadlineSeconds: 60 66 | jobTemplate: 67 | spec: 68 | template: 69 | metadata: 70 | labels: 71 | app: bigbucket-cleaner 72 | spec: 73 | restartPolicy: Never 74 | containers: 75 | - name: bigbucket-cleaner 76 | image: ghcr.io/adrianchifor/bigbucket:latest 77 | imagePullPolicy: Always 78 | env: 79 | - name: BUCKET 80 | value: gs://your-bucket 81 | - name: CLEANER 82 | value: "true" 83 | resources: 84 | requests: 85 | cpu: 50m 86 | memory: 128Mi 87 | -------------------------------------------------------------------------------- /deploy/run.yaml: -------------------------------------------------------------------------------- 1 | # Config for https://github.com/adrianchifor/run-marathon 2 | project: your_project 3 | region: your_region 4 | 5 | allow-invoke: 6 | - user:your_user@company.com 7 | 8 | bigbucket-api: 9 | dir: .. 10 | image: gcr.io/${project}/bigbucket:latest 11 | concurrency: 50 12 | timeout: 30 13 | env: 14 | BUCKET: gs://your_bucket 15 | iam-roles: 16 | # Create/assign role manually if you want more granularity 17 | # SA will be bigbucket-api-sa@your_project.iam.gserviceaccount.com 18 | - roles/storage.objectAdmin 19 | 20 | bigbucket-cleaner: 21 | image: gcr.io/${project}/bigbucket:latest 22 | max-instances: 1 23 | cron: 24 | schedule: 0 * * * * 25 | env: 26 | BUCKET: gs://your_bucket 27 | CLEANER_HTTP: "true" 28 | iam-roles: 29 | # Create/assign role manually if you want more granularity 30 | # SA will be bigbucket-cleaner-sa@your_project.iam.gserviceaccount.com 31 | - roles/storage.objectAdmin 32 | -------------------------------------------------------------------------------- /docs/data_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adrianchifor/Bigbucket/6d467f4d8148c22b575853dc22a6688bf164b124/docs/data_model.png -------------------------------------------------------------------------------- /docs/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adrianchifor/Bigbucket/6d467f4d8148c22b575853dc22a6688bf164b124/docs/overview.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/adrianchifor/Bigbucket 2 | 3 | go 1.19 4 | 5 | require ( 6 | cloud.google.com/go/storage v1.30.1 7 | github.com/DataDog/zstd v1.5.2 8 | github.com/adrianchifor/go-parallel v0.1.0 9 | github.com/gin-gonic/gin v1.9.1 10 | google.golang.org/api v0.114.0 11 | ) 12 | 13 | require ( 14 | cloud.google.com/go v0.110.0 // indirect 15 | cloud.google.com/go/compute v1.18.0 // indirect 16 | cloud.google.com/go/compute/metadata v0.2.3 // indirect 17 | cloud.google.com/go/iam v0.12.0 // indirect 18 | github.com/bytedance/sonic v1.9.1 // indirect 19 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect 20 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 21 | github.com/gin-contrib/sse v0.1.0 // indirect 22 | github.com/go-playground/locales v0.14.1 // indirect 23 | github.com/go-playground/universal-translator v0.18.1 // indirect 24 | github.com/go-playground/validator/v10 v10.14.0 // indirect 25 | github.com/goccy/go-json v0.10.2 // indirect 26 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect 27 | github.com/golang/protobuf v1.5.2 // indirect 28 | github.com/google/go-cmp v0.5.9 // indirect 29 | github.com/google/uuid v1.3.0 // indirect 30 | github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect 31 | github.com/googleapis/gax-go/v2 v2.7.1 // indirect 32 | github.com/json-iterator/go v1.1.12 // indirect 33 | github.com/klauspost/cpuid/v2 v2.2.4 // indirect 34 | github.com/leodido/go-urn v1.2.4 // indirect 35 | github.com/mattn/go-isatty v0.0.19 // indirect 36 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 37 | github.com/modern-go/reflect2 v1.0.2 // indirect 38 | github.com/pelletier/go-toml/v2 v2.0.8 // indirect 39 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 40 | github.com/ugorji/go/codec v1.2.11 // indirect 41 | go.opencensus.io v0.24.0 // indirect 42 | golang.org/x/arch v0.3.0 // indirect 43 | golang.org/x/crypto v0.9.0 // indirect 44 | golang.org/x/net v0.10.0 // indirect 45 | golang.org/x/oauth2 v0.6.0 // indirect 46 | golang.org/x/sys v0.8.0 // indirect 47 | golang.org/x/text v0.9.0 // indirect 48 | golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect 49 | google.golang.org/appengine v1.6.7 // indirect 50 | google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect 51 | google.golang.org/grpc v1.53.0 // indirect 52 | google.golang.org/protobuf v1.30.0 // indirect 53 | gopkg.in/yaml.v3 v3.0.1 // indirect 54 | ) 55 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | cloud.google.com/go v0.110.0 h1:Zc8gqp3+a9/Eyph2KDmcGaPtbKRIoqq4YTlL4NMD0Ys= 3 | cloud.google.com/go v0.110.0/go.mod h1:SJnCLqQ0FCFGSZMUNUf84MV3Aia54kn7pi8st7tMzaY= 4 | cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= 5 | cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= 6 | cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= 7 | cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= 8 | cloud.google.com/go/iam v0.12.0 h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE= 9 | cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB2GYAY= 10 | cloud.google.com/go/longrunning v0.4.1 h1:v+yFJOfKC3yZdY6ZUI933pIYdhyhV8S3NpWrXWmg7jM= 11 | cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= 12 | cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= 13 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 14 | github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8= 15 | github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= 16 | github.com/adrianchifor/go-parallel v0.1.0 h1:BfvVFodmI1NZJULYmvn/3GNNQ3wDTkfODVmwQtNNbBo= 17 | github.com/adrianchifor/go-parallel v0.1.0/go.mod h1:Dlv5MTv3rmkzNvo1+Gki3AHtEyO566e4WBOZoqxdJT4= 18 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 19 | github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= 20 | github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= 21 | github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= 22 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= 23 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= 24 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 25 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 26 | github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= 27 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 28 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 29 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 30 | github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= 31 | github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= 32 | github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= 33 | github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= 34 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= 35 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 36 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 37 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 38 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= 39 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= 40 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 41 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 42 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 43 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 44 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 45 | github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= 46 | github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 47 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 48 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 49 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 50 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= 51 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= 52 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 53 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 54 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 55 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 56 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 57 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 58 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 59 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 60 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 61 | github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= 62 | github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 63 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 64 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 65 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 66 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 67 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 68 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 69 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 70 | github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 71 | github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 72 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 73 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 74 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 75 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 76 | github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= 77 | github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 78 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 79 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 80 | github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= 81 | github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= 82 | github.com/googleapis/gax-go/v2 v2.7.1 h1:gF4c0zjUP2H/s/hEGyLA3I0fA2ZWjzYiONAD6cvPr8A= 83 | github.com/googleapis/gax-go/v2 v2.7.1/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= 84 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 85 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 86 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 87 | github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= 88 | github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 89 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= 90 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= 91 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= 92 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 93 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 94 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 95 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 96 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 97 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 98 | github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= 99 | github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= 100 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 101 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 102 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 103 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 104 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 105 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 106 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 107 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 108 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 109 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 110 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 111 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 112 | github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= 113 | github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 114 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 115 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 116 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= 117 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 118 | go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= 119 | go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= 120 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 121 | golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= 122 | golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 123 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 124 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 125 | golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= 126 | golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= 127 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 128 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 129 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 130 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 131 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 132 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 133 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 134 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 135 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 136 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= 137 | golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 138 | golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= 139 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 140 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 141 | golang.org/x/oauth2 v0.6.0 h1:Lh8GPgSKBfWSwFvtuWOfeI3aAAnbXTSutYxJiOJFgIw= 142 | golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw= 143 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 144 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 145 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 146 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 147 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 148 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 149 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 150 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 151 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 152 | golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= 153 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 154 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 155 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 156 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 157 | golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= 158 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 159 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 160 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 161 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 162 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 163 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 164 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 165 | golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= 166 | golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= 167 | google.golang.org/api v0.114.0 h1:1xQPji6cO2E2vLiI+C/XiFAnsn1WV3mjaEwGLhi3grE= 168 | google.golang.org/api v0.114.0/go.mod h1:ifYI2ZsFK6/uGddGfAD5BMxlnkBqCmqHSDUVi45N5Yg= 169 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 170 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 171 | google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= 172 | google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 173 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 174 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= 175 | google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= 176 | google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= 177 | google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= 178 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 179 | google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= 180 | google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= 181 | google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= 182 | google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= 183 | google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= 184 | google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= 185 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 186 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 187 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 188 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 189 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 190 | google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 191 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 192 | google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 193 | google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= 194 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 195 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 196 | google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= 197 | google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 198 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 199 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 200 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 201 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 202 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 203 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 204 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 205 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 206 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/adrianchifor/Bigbucket/api" 11 | "github.com/adrianchifor/Bigbucket/store" 12 | "github.com/adrianchifor/Bigbucket/worker" 13 | ) 14 | 15 | const version string = "0.2.11" 16 | 17 | var ( 18 | port int 19 | cleanerFlag bool 20 | cleanerInterval int 21 | cleanerHttpFlag bool 22 | versionFlag bool 23 | ) 24 | 25 | func init() { 26 | flag.StringVar(&store.BucketName, "bucket", "", "Bucket name (required, e.g. gs://)") 27 | flag.IntVar(&port, "port", 0, "Server port (default 8080)") 28 | flag.BoolVar(&cleanerFlag, "cleaner", false, "Run Bigbucket in cleaner mode (default false). "+ 29 | "Will garbage collect tables and columns marked for deletion. Executes based on --cleaner-interval") 30 | flag.IntVar(&cleanerInterval, "cleaner-interval", 0, "Bigbucket cleaner interval (default 0, runs only once). "+ 31 | "To run cleaner every hour, you can set --cleaner-interval 3600") 32 | flag.BoolVar(&cleanerHttpFlag, "cleaner-http", false, "Run Bigbucket in cleaner HTTP mode (default false). "+ 33 | "Executes on HTTP POST to /; to be used with https://cloud.google.com/scheduler/docs/creating") 34 | flag.BoolVar(&versionFlag, "version", false, "Version") 35 | flag.Parse() 36 | } 37 | 38 | func main() { 39 | if versionFlag { 40 | fmt.Println("Bigbucket version", version) 41 | os.Exit(0) 42 | } 43 | if cleanerFlag && cleanerHttpFlag { 44 | fmt.Println("Specify only one of --cleaner or --cleaner-http. To run immediately, use --cleaner. " + 45 | "For Cloud Scheduler, use --cleaner-http") 46 | os.Exit(1) 47 | } 48 | 49 | parseEnvVars() 50 | initBucket() 51 | 52 | if cleanerFlag { 53 | worker.RunCleaner(cleanerInterval) 54 | os.Exit(0) 55 | } 56 | if cleanerHttpFlag { 57 | worker.RunCleanerHttp(port) 58 | os.Exit(0) 59 | } 60 | 61 | api.RunServer(port) 62 | } 63 | 64 | func parseEnvVars() { 65 | if store.BucketName == "" { 66 | if value, ok := os.LookupEnv("BUCKET"); ok { 67 | store.BucketName = value 68 | } else { 69 | flag.PrintDefaults() 70 | os.Exit(1) 71 | } 72 | } 73 | 74 | if port == 0 { 75 | if value, ok := os.LookupEnv("PORT"); ok { 76 | valueInt, err := strconv.Atoi(value) 77 | if err != nil { 78 | fmt.Println("'PORT' environment variable cannot be cast to integer") 79 | os.Exit(1) 80 | } 81 | port = valueInt 82 | } else { 83 | // Use default is neither --port / PORT are defined 84 | port = 8080 85 | } 86 | } 87 | 88 | if !cleanerFlag { 89 | if _, ok := os.LookupEnv("CLEANER"); ok { 90 | cleanerFlag = true 91 | } 92 | } 93 | 94 | if cleanerInterval == 0 { 95 | if value, ok := os.LookupEnv("CLEANER_INTERVAL"); ok { 96 | valueInt, err := strconv.Atoi(value) 97 | if err != nil { 98 | fmt.Println("'CLEANER_INTERVAL' environment variable cannot be cast to integer") 99 | os.Exit(1) 100 | } 101 | cleanerInterval = valueInt 102 | } 103 | } 104 | 105 | if !cleanerHttpFlag && !cleanerFlag { 106 | if _, ok := os.LookupEnv("CLEANER_HTTP"); ok { 107 | cleanerHttpFlag = true 108 | } 109 | } 110 | } 111 | 112 | func initBucket() { 113 | if strings.HasPrefix(store.BucketName, "gs://") { 114 | store.BucketName = strings.Replace(store.BucketName, "gs://", "", 1) 115 | store.InitGoog() 116 | } else if strings.HasPrefix(store.BucketName, "s3://") { 117 | // TODO: Implement S3 backend 118 | fmt.Println("S3 bucket backend is not yet implemented") 119 | os.Exit(1) 120 | } else { 121 | fmt.Println("--bucket flag or 'BUCKET' env supports Google Cloud Storage as 'gs://'") 122 | os.Exit(1) 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /store/gcs_bucket.go: -------------------------------------------------------------------------------- 1 | package store 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "io/ioutil" 7 | "log" 8 | "time" 9 | 10 | "cloud.google.com/go/storage" 11 | "github.com/DataDog/zstd" 12 | "google.golang.org/api/iterator" 13 | ) 14 | 15 | var ( 16 | // BucketName is the GCS bucket name 17 | BucketName string 18 | googBucket storage.BucketHandle 19 | ) 20 | 21 | // InitGoog initializes the GCS bucket client 22 | func InitGoog() { 23 | gcsClient, err := storage.NewClient(context.Background()) 24 | if err != nil { 25 | log.Fatalf("Failed to create Google Storage client: %v", err) 26 | } 27 | 28 | googBucket = *gcsClient.Bucket(BucketName) 29 | } 30 | 31 | // ListObjects lists objects in GCS bucket 32 | func ListObjects(prefix string, delimiter string, limit int) ([]string, error) { 33 | ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*30) 34 | defer cancel() 35 | 36 | query := &storage.Query{Prefix: prefix, Delimiter: delimiter} 37 | it := googBucket.Objects(ctxTimeout, query) 38 | 39 | var objects []string 40 | count := 0 41 | for { 42 | if limit > 0 && count == limit { 43 | return objects, nil 44 | } 45 | attrs, err := it.Next() 46 | if err == iterator.Done { 47 | break 48 | } 49 | if err != nil { 50 | return nil, err 51 | } 52 | if delimiter != "" { 53 | objects = append(objects, attrs.Prefix) 54 | } else { 55 | objects = append(objects, attrs.Name) 56 | } 57 | count++ 58 | } 59 | 60 | return objects, nil 61 | } 62 | 63 | // WriteObject writes data to GCS object, will be compressed with zstd 64 | func WriteObject(object string, data []byte) error { 65 | if len(object) == 0 { 66 | return errors.New("store.WriteObject: object cannot be empty string") 67 | } 68 | if data == nil { 69 | return errors.New("store.WriteObject: data cannot be nil") 70 | } 71 | 72 | compressedData, err := zstd.Compress(nil, data) 73 | if err != nil { 74 | return err 75 | } 76 | 77 | ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*30) 78 | defer cancel() 79 | 80 | obj := googBucket.Object(object) 81 | 82 | w := obj.NewWriter(ctxTimeout) 83 | w.Write(compressedData) 84 | 85 | if err := w.Close(); err != nil { 86 | return err 87 | } 88 | 89 | return nil 90 | } 91 | 92 | // ReadObject reads data from GCS object, will be automatically decompressed 93 | func ReadObject(object string) ([]byte, error) { 94 | if len(object) == 0 { 95 | return nil, errors.New("store.ReadObject: object cannot be empty string") 96 | } 97 | 98 | ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*30) 99 | defer cancel() 100 | 101 | obj := googBucket.Object(object) 102 | 103 | r, err := obj.NewReader(ctxTimeout) 104 | if err != nil { 105 | return nil, err 106 | } 107 | defer r.Close() 108 | 109 | compressedData, err := ioutil.ReadAll(r) 110 | if err != nil { 111 | return nil, err 112 | } 113 | data, err := zstd.Decompress(nil, compressedData) 114 | if err != nil { 115 | return nil, err 116 | } 117 | return data, nil 118 | } 119 | 120 | // DeleteObject deletes a GCS object 121 | func DeleteObject(object string) error { 122 | if len(object) == 0 { 123 | return errors.New("store.DeleteObject: object cannot be empty string") 124 | } 125 | 126 | ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*10) 127 | defer cancel() 128 | 129 | obj := googBucket.Object(object) 130 | 131 | if err := obj.Delete(ctxTimeout); err != nil { 132 | return err 133 | } 134 | 135 | return nil 136 | } 137 | -------------------------------------------------------------------------------- /tests/cleaner_http_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "testing" 9 | ) 10 | 11 | func TestCleanerHttp(t *testing.T) { 12 | if err := deleteTable(); err != nil { 13 | t.Error(err) 14 | } 15 | } 16 | 17 | func deleteTable() error { 18 | client := &http.Client{} 19 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/table?table=test1", bytes.NewBuffer([]byte(""))) 20 | if err != nil { 21 | return err 22 | } 23 | resp, err := client.Do(req) 24 | if err != nil { 25 | return err 26 | } 27 | if resp.StatusCode != 200 { 28 | return errors.New("deleteTable /api/table DELETE response status code is not 200") 29 | } 30 | 31 | resp, err = http.Get("http://127.0.0.1:8080/api/table") 32 | if err != nil { 33 | return err 34 | } 35 | if resp.StatusCode != 200 { 36 | return errors.New("deleteTable /api/table GET response status code is not 200") 37 | } 38 | 39 | defer resp.Body.Close() 40 | var dataTable map[string][]string 41 | json.NewDecoder(resp.Body).Decode(&dataTable) 42 | 43 | if len(dataTable["tables"]) != 0 { 44 | return errors.New("deleteTable table was not marked as deleted") 45 | } 46 | 47 | resp, err = http.Post("http://127.0.0.1:8081/", "application/json", bytes.NewBuffer([]byte(""))) 48 | if err != nil { 49 | return err 50 | } 51 | if resp.StatusCode != 200 { 52 | return errors.New("deleteTable cleaner-http / POST response status code is not 200") 53 | } 54 | 55 | resp, err = http.Get("http://127.0.0.1:8080/api/row?table=test1") 56 | if err != nil { 57 | return err 58 | } 59 | if resp.StatusCode != 404 { 60 | return errors.New("deleteTable /api/row GET response status code is not 404") 61 | } 62 | 63 | return nil 64 | } 65 | -------------------------------------------------------------------------------- /tests/cleaner_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | func TestCleaner(t *testing.T) { 13 | if err := deleteColumn(); err != nil { 14 | t.Error(err) 15 | } 16 | } 17 | 18 | func deleteColumn() error { 19 | client := &http.Client{} 20 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/column?table=test1&column=col1", bytes.NewBuffer([]byte(""))) 21 | if err != nil { 22 | return err 23 | } 24 | resp, err := client.Do(req) 25 | if err != nil { 26 | return err 27 | } 28 | if resp.StatusCode != 200 { 29 | return errors.New("deleteColumn /api/column DELETE response status code is not 200") 30 | } 31 | 32 | resp, err = http.Get("http://127.0.0.1:8080/api/column?table=test1") 33 | if err != nil { 34 | return err 35 | } 36 | if resp.StatusCode != 200 { 37 | return errors.New("deleteColumn /api/column GET response status code is not 200") 38 | } 39 | 40 | defer resp.Body.Close() 41 | var dataColumn map[string][]string 42 | json.NewDecoder(resp.Body).Decode(&dataColumn) 43 | 44 | if len(dataColumn["columns"]) != 3 || dataColumn["columns"][0] != "col2" { 45 | return errors.New("deleteColumn column was not marked as deleted") 46 | } 47 | 48 | // Wait 6s for cleaner to trigger 49 | time.Sleep(6 * time.Second) 50 | 51 | resp, err = http.Get("http://127.0.0.1:8080/api/row?table=test1&key=rowkey1") 52 | if err != nil { 53 | return err 54 | } 55 | if resp.StatusCode != 200 { 56 | return errors.New("deleteColumn /api/row GET response status code is not 200") 57 | } 58 | 59 | defer resp.Body.Close() 60 | var dataRow map[string]map[string]string 61 | json.NewDecoder(resp.Body).Decode(&dataRow) 62 | 63 | if len(dataRow["rowkey1"]) != 3 { 64 | return errors.New("deleteColumn response body still has all columns") 65 | } 66 | 67 | return nil 68 | } 69 | -------------------------------------------------------------------------------- /tests/column_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "testing" 9 | ) 10 | 11 | func TestColumns(t *testing.T) { 12 | if err := listColumns(); err != nil { 13 | t.Error(err) 14 | } 15 | if err := listColumnsBadParams(); err != nil { 16 | t.Error(err) 17 | } 18 | if err := deleteColumnBadParams(); err != nil { 19 | t.Error(err) 20 | } 21 | } 22 | 23 | func listColumns() error { 24 | resp, err := http.Get("http://127.0.0.1:8080/api/column?table=test1") 25 | if err != nil { 26 | return err 27 | } 28 | if resp.StatusCode != 200 { 29 | return errors.New("listColumns /api/column GET response status code is not 200") 30 | } 31 | 32 | defer resp.Body.Close() 33 | var data map[string][]string 34 | json.NewDecoder(resp.Body).Decode(&data) 35 | 36 | if len(data["columns"]) != 4 || data["columns"][0] != "col1" { 37 | return errors.New("listColumns columns do not match those set") 38 | } 39 | return nil 40 | } 41 | 42 | func listColumnsBadParams() error { 43 | resp, err := http.Get("http://127.0.0.1:8080/api/column") 44 | if err != nil { 45 | return err 46 | } 47 | if resp.StatusCode != 400 { 48 | return errors.New("listColumnsBadParams /api/column GET (no table) response status code is not 400") 49 | } 50 | 51 | return nil 52 | } 53 | 54 | func deleteColumnBadParams() error { 55 | client := &http.Client{} 56 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/column", bytes.NewBuffer([]byte(""))) 57 | if err != nil { 58 | return err 59 | } 60 | resp, err := client.Do(req) 61 | if err != nil { 62 | return err 63 | } 64 | if resp.StatusCode != 400 { 65 | return errors.New("deleteColumnBadParams /api/column DELETE (no table) response status code is not 400") 66 | } 67 | 68 | req, err = http.NewRequest("DELETE", "http://127.0.0.1:8080/api/column?table=test1", bytes.NewBuffer([]byte(""))) 69 | if err != nil { 70 | return err 71 | } 72 | resp, err = client.Do(req) 73 | if err != nil { 74 | return err 75 | } 76 | if resp.StatusCode != 400 { 77 | return errors.New("deleteColumnBadParams /api/column DELETE (no column) response status code is not 400") 78 | } 79 | 80 | return nil 81 | } 82 | -------------------------------------------------------------------------------- /tests/row_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "net/http" 9 | "sort" 10 | "testing" 11 | ) 12 | 13 | func TestRows(t *testing.T) { 14 | if err := setRows(); err != nil { 15 | t.Error(err) 16 | } 17 | if err := setRowsBadParams(); err != nil { 18 | t.Error(err) 19 | } 20 | if err := readSingleRow(); err != nil { 21 | t.Error(err) 22 | } 23 | if err := readSingleRowColumn(); err != nil { 24 | t.Error(err) 25 | } 26 | if err := readAllRows(); err != nil { 27 | t.Error(err) 28 | } 29 | if err := readRowsWithPrefix(); err != nil { 30 | t.Error(err) 31 | } 32 | if err := readRowsWithColumns(); err != nil { 33 | t.Error(err) 34 | } 35 | if err := readRowsWithLimit(); err != nil { 36 | t.Error(err) 37 | } 38 | if err := readRowsBadParams(); err != nil { 39 | t.Error(err) 40 | } 41 | if err := listRows(); err != nil { 42 | t.Error(err) 43 | } 44 | if err := listRowsWithPrefix(); err != nil { 45 | t.Error(err) 46 | } 47 | if err := listRowsBadParams(); err != nil { 48 | t.Error(err) 49 | } 50 | if err := countRows(); err != nil { 51 | t.Error(err) 52 | } 53 | if err := countRowsBadParams(); err != nil { 54 | t.Error(err) 55 | } 56 | if err := deleteSingleRow(); err != nil { 57 | t.Error(err) 58 | } 59 | if err := deleteRowsPrefix(); err != nil { 60 | t.Error(err) 61 | } 62 | if err := deleteRowsBadParams(); err != nil { 63 | t.Error(err) 64 | } 65 | } 66 | 67 | func setRows() error { 68 | reqBody, err := json.Marshal(map[string]string{ 69 | "col1": "qwerty1", 70 | "col2": "qwerty2", 71 | "col3": "qwerty3", 72 | "col4": "qwerty4", 73 | }) 74 | if err != nil { 75 | return err 76 | } 77 | 78 | keys := []string{"key", "rowkey"} 79 | for i := 0; i < 10; i++ { 80 | for _, key := range keys { 81 | resp, err := http.Post(fmt.Sprintf("http://127.0.0.1:8080/api/row?table=test1&key=%s%d", key, i), 82 | "application/json", bytes.NewBuffer(reqBody)) 83 | if err != nil { 84 | return err 85 | } 86 | if resp.StatusCode != 200 { 87 | return errors.New("setRows /api/row POST response status code is not 200") 88 | } 89 | } 90 | } 91 | 92 | return nil 93 | } 94 | 95 | func setRowsBadParams() error { 96 | resp, err := http.Post("http://127.0.0.1:8080/api/row", "application/json", bytes.NewBuffer([]byte(""))) 97 | if err != nil { 98 | return err 99 | } 100 | if resp.StatusCode != 400 { 101 | return errors.New("setRowsBadParams /api/row POST (no table) response status code is not 400") 102 | } 103 | 104 | resp, err = http.Post("http://127.0.0.1:8080/api/row?table=test1", "application/json", 105 | bytes.NewBuffer([]byte(""))) 106 | if err != nil { 107 | return err 108 | } 109 | if resp.StatusCode != 400 { 110 | return errors.New("setRowsBadParams /api/row POST (no key) response status code is not 400") 111 | } 112 | 113 | reqBody, err := json.Marshal(map[string]interface{}{ 114 | "col1": 1, // Value not a string 115 | }) 116 | if err != nil { 117 | return err 118 | } 119 | resp, err = http.Post("http://127.0.0.1:8080/api/row?table=test1&key=key0", "application/json", 120 | bytes.NewBuffer(reqBody)) 121 | if err != nil { 122 | return err 123 | } 124 | if resp.StatusCode != 400 { 125 | return errors.New("setRowsBadParams /api/row POST (bad json, int value) response status code is not 400") 126 | } 127 | 128 | reqBody, err = json.Marshal(map[string]interface{}{ 129 | "col1/": "test", // Invalid column name 130 | }) 131 | if err != nil { 132 | return err 133 | } 134 | resp, err = http.Post("http://127.0.0.1:8080/api/row?table=test1&key=key0", "application/json", 135 | bytes.NewBuffer(reqBody)) 136 | if err != nil { 137 | return err 138 | } 139 | if resp.StatusCode != 400 { 140 | return errors.New("setRowsBadParams /api/row POST (bad json, invalid column) response status code is not 400") 141 | } 142 | 143 | return nil 144 | } 145 | 146 | func readSingleRow() error { 147 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1&key=key1") 148 | if err != nil { 149 | return err 150 | } 151 | if resp.StatusCode != 200 { 152 | return errors.New("readSingleRow /api/row GET response status code is not 200") 153 | } 154 | 155 | defer resp.Body.Close() 156 | var data map[string]map[string]string 157 | json.NewDecoder(resp.Body).Decode(&data) 158 | 159 | if len(data) != 1 { 160 | return errors.New("readSingleRow response body doesn't have exactly one row") 161 | } 162 | if len(data["key1"]) != 4 { 163 | return errors.New("readSingleRow response body doesn't have all columns") 164 | } 165 | return nil 166 | } 167 | 168 | func readSingleRowColumn() error { 169 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1&key=key1&columns=col2") 170 | if err != nil { 171 | return err 172 | } 173 | if resp.StatusCode != 200 { 174 | return errors.New("readSingleRowColumn /api/row GET response status code is not 200") 175 | } 176 | 177 | defer resp.Body.Close() 178 | var data map[string]map[string]string 179 | json.NewDecoder(resp.Body).Decode(&data) 180 | 181 | if len(data) != 1 { 182 | return errors.New("readSingleRowColumn response body doesn't have exactly one row") 183 | } 184 | if len(data["key1"]) != 1 { 185 | return errors.New("readSingleRowColumn response body doesn't have exactly one column") 186 | } 187 | if data["key1"]["col2"] != "qwerty2" { 188 | return errors.New("readSingleRowColumn key1/col2 value incorrect") 189 | } 190 | return nil 191 | } 192 | 193 | func readAllRows() error { 194 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1") 195 | if err != nil { 196 | return err 197 | } 198 | if resp.StatusCode != 200 { 199 | return errors.New("readAllRows /api/row GET response status code is not 200") 200 | } 201 | 202 | defer resp.Body.Close() 203 | var data map[string]map[string]string 204 | json.NewDecoder(resp.Body).Decode(&data) 205 | 206 | if len(data) < 20 { 207 | return errors.New("readAllRows response body doesn't have all rows") 208 | } 209 | if data["key1"]["col2"] != "qwerty2" { 210 | return errors.New("readAllRows key1/col2 value incorrect") 211 | } 212 | return nil 213 | } 214 | 215 | func readRowsWithPrefix() error { 216 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1&prefix=key") 217 | if err != nil { 218 | return err 219 | } 220 | if resp.StatusCode != 200 { 221 | return errors.New("readRowsWithPrefix /api/row GET response status code is not 200") 222 | } 223 | 224 | defer resp.Body.Close() 225 | var data map[string]map[string]string 226 | json.NewDecoder(resp.Body).Decode(&data) 227 | 228 | if len(data) < 10 { 229 | return errors.New("readRowsWithPrefix response body doesn't have all rows") 230 | } 231 | if data["key1"]["col2"] != "qwerty2" { 232 | return errors.New("readRowsWithPrefix key1/col2 value incorrect") 233 | } 234 | return nil 235 | } 236 | 237 | func readRowsWithColumns() error { 238 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1&columns=col1,col2") 239 | if err != nil { 240 | return err 241 | } 242 | if resp.StatusCode != 200 { 243 | return errors.New("readRowsWithColumns /api/row GET response status code is not 200") 244 | } 245 | 246 | defer resp.Body.Close() 247 | var data map[string]map[string]string 248 | json.NewDecoder(resp.Body).Decode(&data) 249 | 250 | if len(data) < 20 { 251 | return errors.New("readRowsWithColumns response body doesn't have all rows") 252 | } 253 | for col := range data["key1"] { 254 | if col != "col1" && col != "col2" { 255 | return errors.New("readRowsWithColumns got columns other than requested") 256 | } 257 | } 258 | return nil 259 | } 260 | 261 | func readRowsWithLimit() error { 262 | resp, err := http.Get("http://127.0.0.1:8080/api/row?table=test1&limit=2") 263 | if err != nil { 264 | return err 265 | } 266 | if resp.StatusCode != 200 { 267 | return errors.New("readRowsWithLimit /api/row GET response status code is not 200") 268 | } 269 | 270 | defer resp.Body.Close() 271 | var data map[string]map[string]string 272 | json.NewDecoder(resp.Body).Decode(&data) 273 | 274 | if len(data) > 2 { 275 | return errors.New("readRowsWithLimit response body has more rows than limit") 276 | } 277 | // Check keys returned are sorted 278 | keys := []string{} 279 | for key := range data { 280 | keys = append(keys, key) 281 | } 282 | if !sort.StringsAreSorted(keys) { 283 | return errors.New("readRowsWithLimit response keys are not sorted") 284 | } 285 | return nil 286 | } 287 | 288 | func readRowsBadParams() error { 289 | resp, err := http.Get("http://127.0.0.1:8080/api/row") 290 | if err != nil { 291 | return err 292 | } 293 | if resp.StatusCode != 400 { 294 | return errors.New("readRowsBadParams /api/row GET (no table) response status code is not 400") 295 | } 296 | 297 | resp, err = http.Get("http://127.0.0.1:8080/api/row?table=test1&key=key1&prefix=key") 298 | if err != nil { 299 | return err 300 | } 301 | if resp.StatusCode != 400 { 302 | return errors.New("readRowsBadParams /api/row GET (both key and prefix) response status code is not 400") 303 | } 304 | 305 | return nil 306 | } 307 | 308 | func listRows() error { 309 | resp, err := http.Get("http://127.0.0.1:8080/api/row/list?table=test1") 310 | if err != nil { 311 | return err 312 | } 313 | if resp.StatusCode != 200 { 314 | return errors.New("listRows /api/row/list GET response status code is not 200") 315 | } 316 | 317 | defer resp.Body.Close() 318 | var data map[string][]string 319 | json.NewDecoder(resp.Body).Decode(&data) 320 | 321 | if len(data["rowKeys"]) != 20 { 322 | return errors.New("listRows count doesn't match what was set") 323 | } 324 | return nil 325 | } 326 | 327 | func listRowsWithPrefix() error { 328 | resp, err := http.Get("http://127.0.0.1:8080/api/row/list?table=test1&prefix=key") 329 | if err != nil { 330 | return err 331 | } 332 | if resp.StatusCode != 200 { 333 | return errors.New("listRowsWithPrefix /api/row/list GET response status code is not 200") 334 | } 335 | 336 | defer resp.Body.Close() 337 | var data map[string][]string 338 | json.NewDecoder(resp.Body).Decode(&data) 339 | 340 | if len(data["rowKeys"]) != 10 { 341 | return errors.New("listRowsWithPrefix count doesn't match what was set") 342 | } 343 | return nil 344 | } 345 | 346 | func listRowsBadParams() error { 347 | resp, err := http.Get("http://127.0.0.1:8080/api/row/list") 348 | if err != nil { 349 | return err 350 | } 351 | if resp.StatusCode != 400 { 352 | return errors.New("listRowsBadParams /api/row/list GET (no table) response status code is not 400") 353 | } 354 | 355 | return nil 356 | } 357 | 358 | func countRows() error { 359 | resp, err := http.Get("http://127.0.0.1:8080/api/row/count?table=test1") 360 | if err != nil { 361 | return err 362 | } 363 | if resp.StatusCode != 200 { 364 | return errors.New("countRows /api/row/count GET response status code is not 200") 365 | } 366 | 367 | defer resp.Body.Close() 368 | var data map[string]string 369 | json.NewDecoder(resp.Body).Decode(&data) 370 | 371 | if data["rowsCount"] != "20" { 372 | return errors.New("countRows count doesn't match what was set") 373 | } 374 | return nil 375 | } 376 | 377 | func countRowsBadParams() error { 378 | resp, err := http.Get("http://127.0.0.1:8080/api/row/count") 379 | if err != nil { 380 | return err 381 | } 382 | if resp.StatusCode != 400 { 383 | return errors.New("countRowsBadParams /api/row/count GET (no table) response status code is not 400") 384 | } 385 | 386 | return nil 387 | } 388 | 389 | func deleteSingleRow() error { 390 | client := &http.Client{} 391 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/row?table=test1&key=key0", bytes.NewBuffer([]byte(""))) 392 | if err != nil { 393 | return err 394 | } 395 | resp, err := client.Do(req) 396 | if err != nil { 397 | return err 398 | } 399 | if resp.StatusCode != 200 { 400 | return errors.New("deleteSingleRow /api/row DELETE response status code is not 200") 401 | } 402 | 403 | resp, err = http.Get("http://127.0.0.1:8080/api/row?table=test1&key=key0") 404 | if err != nil { 405 | return err 406 | } 407 | if resp.StatusCode != 404 { 408 | return errors.New("deleteSingleRow /api/row GET response status code is not 404") 409 | } 410 | 411 | return nil 412 | } 413 | 414 | func deleteRowsPrefix() error { 415 | client := &http.Client{} 416 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/row?table=test1&prefix=key", bytes.NewBuffer([]byte(""))) 417 | if err != nil { 418 | return err 419 | } 420 | resp, err := client.Do(req) 421 | if err != nil { 422 | return err 423 | } 424 | if resp.StatusCode != 200 { 425 | return errors.New("deleteRowsPrefix /api/row DELETE response status code is not 200") 426 | } 427 | 428 | resp, err = http.Get("http://127.0.0.1:8080/api/row?table=test1&prefix=key") 429 | if err != nil { 430 | return err 431 | } 432 | if resp.StatusCode != 404 { 433 | return errors.New("deleteRowsPrefix /api/row GET response status code is not 404") 434 | } 435 | 436 | return nil 437 | } 438 | 439 | func deleteRowsBadParams() error { 440 | client := &http.Client{} 441 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/row", bytes.NewBuffer([]byte(""))) 442 | if err != nil { 443 | return err 444 | } 445 | resp, err := client.Do(req) 446 | if err != nil { 447 | return err 448 | } 449 | if resp.StatusCode != 400 { 450 | return errors.New("deleteRowsBadParams /api/row DELETE (no table) response status code is not 400") 451 | } 452 | 453 | req, err = http.NewRequest("DELETE", "http://127.0.0.1:8080/api/row?table=test1&key=key1&prefix=key", bytes.NewBuffer([]byte(""))) 454 | if err != nil { 455 | return err 456 | } 457 | resp, err = client.Do(req) 458 | if err != nil { 459 | return err 460 | } 461 | if resp.StatusCode != 400 { 462 | return errors.New("deleteRowsBadParams /api/row DELETE (both key and prefix) response status code is not 400") 463 | } 464 | 465 | return nil 466 | } 467 | -------------------------------------------------------------------------------- /tests/run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # ./run_tests.sh 4 | 5 | set -u 6 | set -eE 7 | 8 | BUCKET="$1" 9 | 10 | function cleanup() { 11 | echo -e "\nCleaning up test bucket" 12 | gsutil rm -r "$BUCKET/bigbucket" > /dev/null 2>&1 || true 13 | 14 | echo "Cleaning up bigbucket processes" 15 | for process in $(pgrep bigbucket); do 16 | kill "$process" 17 | done 18 | echo "Done" 19 | } 20 | 21 | trap cleanup ERR 22 | 23 | # Get directory of script no matter where it's called from 24 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 25 | 26 | echo -e "\nRunning bigbucket server" 27 | $DIR/../bin/bigbucket --bucket "$BUCKET" > /dev/null 2>&1 & 28 | 29 | echo -e "\nRunning row tests" 30 | go test $DIR/row_test.go 31 | 32 | echo -e "\nRunning column tests" 33 | go test $DIR/column_test.go 34 | 35 | echo -e "\nRunning table tests" 36 | go test $DIR/table_test.go 37 | 38 | echo -e "\nRunning bigbucket cleaner" 39 | $DIR/../bin/bigbucket --bucket "$BUCKET" --cleaner --cleaner-interval 3 > /dev/null 2>&1 & 40 | 41 | echo -e "\nRunning bigbucket cleaner tests" 42 | go test $DIR/cleaner_test.go 43 | 44 | echo -e "\nKilling bigbucket cleaner" 45 | kill "$!" 46 | 47 | echo -e "\nRunning bigbucket cleaner as HTTP server" 48 | $DIR/../bin/bigbucket --bucket "$BUCKET" --cleaner-http --port 8081 > /dev/null 2>&1 & 49 | 50 | echo -e "\nRunning HTTP cleaner tests" 51 | go test $DIR/cleaner_http_test.go 52 | 53 | cleanup 54 | 55 | 56 | -------------------------------------------------------------------------------- /tests/table_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "testing" 9 | ) 10 | 11 | func TestTables(t *testing.T) { 12 | if err := listTables(); err != nil { 13 | t.Error(err) 14 | } 15 | if err := deleteTableBadParams(); err != nil { 16 | t.Error(err) 17 | } 18 | } 19 | 20 | func listTables() error { 21 | resp, err := http.Get("http://127.0.0.1:8080/api/table") 22 | if err != nil { 23 | return err 24 | } 25 | if resp.StatusCode != 200 { 26 | return errors.New("listTables /api/table GET response status code is not 200") 27 | } 28 | 29 | defer resp.Body.Close() 30 | var data map[string][]string 31 | json.NewDecoder(resp.Body).Decode(&data) 32 | 33 | if len(data["tables"]) != 1 || data["tables"][0] != "test1" { 34 | return errors.New("listTables tables do not match those set") 35 | } 36 | return nil 37 | } 38 | 39 | func deleteTableBadParams() error { 40 | client := &http.Client{} 41 | req, err := http.NewRequest("DELETE", "http://127.0.0.1:8080/api/table", bytes.NewBuffer([]byte(""))) 42 | if err != nil { 43 | return err 44 | } 45 | resp, err := client.Do(req) 46 | if err != nil { 47 | return err 48 | } 49 | if resp.StatusCode != 400 { 50 | return errors.New("deleteTableBadParams /api/table DELETE (no table) response status code is not 400") 51 | } 52 | 53 | return nil 54 | } 55 | -------------------------------------------------------------------------------- /utils/functions.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // Search returns first index where found, otherwise -1 8 | func Search(list []string, a string) int { 9 | for i, elem := range list { 10 | if elem == a { 11 | return i 12 | } 13 | } 14 | return -1 15 | } 16 | 17 | // RemoveIndex removes item from slice at index 18 | func RemoveIndex(list []string, index int) []string { 19 | list[index] = list[len(list)-1] 20 | list[len(list)-1] = "" 21 | list = list[:len(list)-1] 22 | 23 | return list 24 | } 25 | 26 | // MergeMaps merges multiple maps into one; duplicate k-v in subsequent maps will override previous ones 27 | func MergeMaps(maps ...map[string]string) map[string]string { 28 | mergedMap := make(map[string]string) 29 | for _, innerMap := range maps { 30 | for k, v := range innerMap { 31 | mergedMap[k] = v 32 | } 33 | } 34 | 35 | return mergedMap 36 | } 37 | 38 | // CleanupTables filters out 'bigbucket' and '/' from tables []string 39 | func CleanupTables(tables []string) []string { 40 | cleanTables := []string{} 41 | for _, table := range tables { 42 | cleanTable := strings.Replace(strings.Replace(table, "bigbucket", "", 1), "/", "", -1) 43 | if cleanTable != "" { 44 | cleanTables = append(cleanTables, cleanTable) 45 | } 46 | } 47 | 48 | return cleanTables 49 | } 50 | -------------------------------------------------------------------------------- /utils/server.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "os" 9 | "os/signal" 10 | "syscall" 11 | "time" 12 | 13 | "github.com/gin-gonic/gin" 14 | ) 15 | 16 | // RunServer creates and runs a new Gin HTTP server with graceful shutdown 17 | func RunServer(port int, router *gin.Engine) { 18 | done := make(chan bool, 1) 19 | quit := make(chan os.Signal, 1) 20 | 21 | signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) 22 | 23 | server, listenAddr := newServer(port, router) 24 | go serverGracefulShutdown(server, quit, done) 25 | 26 | log.Println("HTTP server is ready to handle requests at", listenAddr) 27 | if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { 28 | log.Fatalf("HTTP server could not listen on %s: %v\n", listenAddr, err) 29 | } 30 | 31 | <-done 32 | log.Println("HTTP server stopped") 33 | } 34 | 35 | func newServer(port int, router *gin.Engine) (*http.Server, string) { 36 | listenAddr := fmt.Sprintf("127.0.0.1:%d", port) 37 | 38 | ginMode := os.Getenv("GIN_MODE") 39 | if ginMode == "release" { 40 | listenAddr = fmt.Sprintf(":%d", port) 41 | } 42 | 43 | return &http.Server{ 44 | Addr: listenAddr, 45 | Handler: router, 46 | }, listenAddr 47 | } 48 | 49 | func serverGracefulShutdown(server *http.Server, quit <-chan os.Signal, done chan<- bool) { 50 | <-quit 51 | log.Println("HTTP server is shutting down...") 52 | 53 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 54 | defer cancel() 55 | 56 | server.SetKeepAlivesEnabled(false) 57 | if err := server.Shutdown(ctx); err != nil { 58 | log.Fatalf("Could not gracefully shutdown the HTTP server: %v\n", err) 59 | } 60 | close(done) 61 | } 62 | -------------------------------------------------------------------------------- /utils/state.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | 7 | "github.com/adrianchifor/Bigbucket/store" 8 | ) 9 | 10 | // GetState gets object content as string[] 11 | func GetState(object string) []string { 12 | state := []string{} 13 | 14 | data, err := store.ReadObject(object) 15 | if err != nil { 16 | return state 17 | } 18 | buf := bytes.NewBuffer(data) 19 | gob.NewDecoder(buf).Decode(&state) 20 | 21 | return state 22 | } 23 | 24 | // WriteState writes string[] to object 25 | func WriteState(object string, state []string) error { 26 | buf := &bytes.Buffer{} 27 | gob.NewEncoder(buf).Encode(state) 28 | data := buf.Bytes() 29 | 30 | err := store.WriteObject(object, data) 31 | if err != nil { 32 | return err 33 | } 34 | 35 | return nil 36 | } 37 | -------------------------------------------------------------------------------- /worker/cleaner.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "strings" 10 | "sync" 11 | "syscall" 12 | "time" 13 | 14 | "github.com/adrianchifor/Bigbucket/store" 15 | "github.com/adrianchifor/Bigbucket/utils" 16 | "github.com/adrianchifor/go-parallel" 17 | "github.com/gin-gonic/gin" 18 | ) 19 | 20 | var ( 21 | stopCleaner = false 22 | stopCleanerMutex = &sync.Mutex{} 23 | ) 24 | 25 | // RunCleaner runs the cleaner once or on an interval 26 | func RunCleaner(interval int) { 27 | done := make(chan bool, 1) 28 | quit := make(chan os.Signal, 1) 29 | 30 | signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) 31 | 32 | deleteJobPool := parallel.LargeJobPool() 33 | defer deleteJobPool.Close() 34 | 35 | go cleanerGracefulShutdown(deleteJobPool, quit, done) 36 | 37 | log.Printf("Running cleaner...") 38 | cleanupTables(deleteJobPool) 39 | cleanupColumns(deleteJobPool) 40 | 41 | if interval > 0 { 42 | log.Printf("Running cleaner every %d seconds...", interval) 43 | ticker := time.NewTicker(time.Second * time.Duration(interval)) 44 | defer ticker.Stop() 45 | loop: 46 | for { 47 | select { 48 | case <-ticker.C: 49 | cleanupTables(deleteJobPool) 50 | cleanupColumns(deleteJobPool) 51 | case <-done: 52 | log.Println("Cleaner schedule has been cancelled") 53 | break loop 54 | } 55 | } 56 | } 57 | 58 | log.Println("Cleaner process done") 59 | } 60 | 61 | // RunCleanerHttp runs an HTTP server+router for cleaner 62 | func RunCleanerHttp(port int) { 63 | deleteJobPool := parallel.LargeJobPool() 64 | defer deleteJobPool.Close() 65 | 66 | router := gin.Default() 67 | 68 | router.POST("/", func(c *gin.Context) { 69 | log.Printf("Running cleaner...") 70 | cleanupTables(deleteJobPool) 71 | cleanupColumns(deleteJobPool) 72 | c.String(200, "OK") 73 | }) 74 | router.GET("/health", func(c *gin.Context) { 75 | c.String(200, "UP") 76 | }) 77 | 78 | utils.RunServer(port, router) 79 | } 80 | 81 | func cleanerGracefulShutdown(jobPool *parallel.JobPool, quit <-chan os.Signal, done chan<- bool) { 82 | <-quit 83 | log.Println("Cleaner process is shutting down...") 84 | 85 | stopCleanerMutex.Lock() 86 | stopCleaner = true 87 | stopCleanerMutex.Unlock() 88 | 89 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 90 | defer cancel() 91 | 92 | err := jobPool.WaitContext(ctx) 93 | if err != nil { 94 | log.Fatalf("Could not gracefully shutdown the cleaner process: %v\n", err) 95 | } 96 | close(done) 97 | } 98 | 99 | func cleanupTables(jobPool *parallel.JobPool) { 100 | tablesToDelete := utils.GetState("bigbucket/.delete_tables") 101 | if len(tablesToDelete) == 0 { 102 | return 103 | } 104 | 105 | for i, table := range tablesToDelete { 106 | objects, err := store.ListObjects(fmt.Sprintf("bigbucket/%s/", table), "", 0) 107 | if err != nil { 108 | log.Printf("Failed to list objects in table '%s': %v", table, err) 109 | continue 110 | } 111 | if len(objects) == 0 { 112 | err := utils.WriteState("bigbucket/.delete_tables", utils.RemoveIndex(tablesToDelete, i)) 113 | if err != nil { 114 | log.Printf("Failed to update .delete_tables state: %v", err) 115 | } else { 116 | log.Printf("Table '%s' cleaned up", table) 117 | } 118 | continue 119 | } 120 | 121 | for _, object := range objects { 122 | object := object 123 | jobPool.AddJob(func() { 124 | stopCleanerMutex.Lock() 125 | if stopCleaner { 126 | stopCleanerMutex.Unlock() 127 | return 128 | } 129 | stopCleanerMutex.Unlock() 130 | 131 | store.DeleteObject(object) 132 | }) 133 | } 134 | } 135 | 136 | jobPool.Wait() 137 | // Double check objects and update deleted tables state if nothing left 138 | cleanupTables(jobPool) 139 | } 140 | 141 | func cleanupColumns(jobPool *parallel.JobPool) { 142 | objects, err := store.ListObjects("bigbucket/", "/", 0) 143 | if err != nil { 144 | log.Printf("Failed to list tables: %v", err) 145 | } 146 | if len(objects) == 0 { 147 | return 148 | } 149 | tables := utils.CleanupTables(objects) 150 | 151 | noColumnsToDelete := true 152 | for _, table := range tables { 153 | columnsToDelete := utils.GetState(fmt.Sprintf("bigbucket/%s/.delete_columns", table)) 154 | if len(columnsToDelete) == 0 { 155 | continue 156 | } 157 | if noColumnsToDelete { 158 | noColumnsToDelete = false 159 | } 160 | 161 | objects, err = store.ListObjects(fmt.Sprintf("bigbucket/%s/", table), "", 0) 162 | if err != nil { 163 | log.Printf("Failed to list objects in table '%s': %v", table, err) 164 | continue 165 | } 166 | 167 | for i, column := range columnsToDelete { 168 | column := column 169 | noColumnsFound := true 170 | 171 | for _, object := range objects { 172 | object := object 173 | if strings.HasSuffix(object, column) { 174 | if noColumnsFound { 175 | noColumnsFound = false 176 | } 177 | 178 | jobPool.AddJob(func() { 179 | stopCleanerMutex.Lock() 180 | if stopCleaner { 181 | stopCleanerMutex.Unlock() 182 | return 183 | } 184 | stopCleanerMutex.Unlock() 185 | 186 | store.DeleteObject(object) 187 | }) 188 | } 189 | } 190 | 191 | jobPool.Wait() 192 | 193 | if noColumnsFound { 194 | err := utils.WriteState(fmt.Sprintf("bigbucket/%s/.delete_columns", table), utils.RemoveIndex(columnsToDelete, i)) 195 | if err != nil { 196 | log.Printf("Failed to update %s/.delete_columns state: %v", table, err) 197 | } else { 198 | log.Printf("Column '%s' in table '%s' cleaned up", column, table) 199 | } 200 | } 201 | } 202 | } 203 | 204 | if noColumnsToDelete { 205 | return 206 | } 207 | // Double check objects and update deleted columns state if nothing left 208 | cleanupColumns(jobPool) 209 | } 210 | --------------------------------------------------------------------------------