diff --git a/go.mod b/go.mod index 67e1a97f63..491bef2b6b 100644 --- a/go.mod +++ b/go.mod @@ -65,6 +65,7 @@ require ( github.com/open-policy-agent/opa v1.6.0 github.com/opencloud-eu/libre-graph-api-go v1.0.8-0.20250724122329-41ba6b191e76 github.com/opencloud-eu/reva/v2 v2.36.1-0.20250827073033-ede93b948fc8 + github.com/opensearch-project/opensearch-go/v4 v4.5.0 github.com/orcaman/concurrent-map v1.0.0 github.com/pkg/errors v0.9.1 github.com/pkg/xattr v0.4.12 @@ -74,6 +75,7 @@ require ( github.com/rogpeppe/go-internal v1.14.1 github.com/rs/cors v1.11.1 github.com/rs/zerolog v1.34.0 + github.com/samber/lo v1.51.0 github.com/sirupsen/logrus v1.9.3 github.com/spf13/afero v1.14.0 github.com/spf13/cobra v1.9.1 diff --git a/go.sum b/go.sum index 8df33a37b2..3d9251e791 100644 --- a/go.sum +++ b/go.sum @@ -868,6 +868,8 @@ github.com/opencloud-eu/libre-graph-api-go v1.0.8-0.20250724122329-41ba6b191e76 github.com/opencloud-eu/libre-graph-api-go v1.0.8-0.20250724122329-41ba6b191e76/go.mod h1:pzatilMEHZFT3qV7C/X3MqOa3NlRQuYhlRhZTL+hN6Q= github.com/opencloud-eu/reva/v2 v2.36.1-0.20250827073033-ede93b948fc8 h1:mvHvhSHJNjoMyvOPf07cUFi7oDe7qpKdJQg/BrEg/fI= github.com/opencloud-eu/reva/v2 v2.36.1-0.20250827073033-ede93b948fc8/go.mod h1:Gcpjslh5OnxS4zJ3HxeLOy7Hz2WOjn0eVemvBj17nlk= +github.com/opensearch-project/opensearch-go/v4 v4.5.0 h1:26XckmmF6MhlXt91Bu1yY6R51jy1Ns/C3XgIfvyeTRo= +github.com/opensearch-project/opensearch-go/v4 v4.5.0/go.mod h1:VmFc7dqOEM3ZtLhrpleOzeq+cqUgNabqQG5gX0xId64= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= @@ -993,6 +995,8 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sacloud/libsacloud v1.36.2/go.mod h1:P7YAOVmnIn3DKHqCZcUKYUXmSwGBm3yS7IBEjKVSrjg= +github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI= +github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210127161313-bd30bebeac4f/go.mod h1:CJJ5VAbozOl0yEw7nHB9+7BXTJbIn6h7W+f6Gau5IP8= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/segmentio/kafka-go v0.4.48 h1:9jyu9CWK4W5W+SroCe8EffbrRZVqAOkuaLd/ApID4Vs= @@ -1090,6 +1094,8 @@ github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JT github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww= github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU= @@ -1120,6 +1126,8 @@ github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21 github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/vultr/govultr/v2 v2.0.0/go.mod h1:2PsEeg+gs3p/Fo5Pw8F9mv+DUBEOlrNZ8GmCTGmhOhs= +github.com/wI2L/jsondiff v0.7.0 h1:1lH1G37GhBPqCfp/lrs91rf/2j3DktX6qYAKZkLuCQQ= +github.com/wI2L/jsondiff v0.7.0/go.mod h1:KAEIojdQq66oJiHhDyQez2x+sRit0vIzC9KeK0yizxM= github.com/wk8/go-ordered-map v1.0.0 h1:BV7z+2PaK8LTSd/mWgY12HyMAo5CEgkHqbkVq2thqr8= github.com/wk8/go-ordered-map v1.0.0/go.mod h1:9ZIbRunKbuvfPKyBP1SIKLcXNlv74YCOZ3t3VTS6gRk= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/.codecov.yml b/vendor/github.com/opensearch-project/opensearch-go/v4/.codecov.yml new file mode 100644 index 0000000000..7b390d3a0e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/.codecov.yml @@ -0,0 +1,15 @@ +# https://docs.codecov.com/docs/pull-request-comments +comment: + layout: "diff, flags, files" + behavior: default + require_changes: false # if true: only post the comment if coverage changes + require_base: false # [true :: must have a base report to post] + require_head: true # [true :: must have a head report to post] + hide_project_coverage: false # [true :: only show coverage on the git diff] + +coverage: + status: + project: + default: + threshold: 5% # allow 5% coverage decrease + patch: off diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/.dockerignore b/vendor/github.com/opensearch-project/opensearch-go/v4/.dockerignore new file mode 100644 index 0000000000..4c8512b085 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/.dockerignore @@ -0,0 +1,2 @@ +.git/ +tmp/ diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/.gitignore b/vendor/github.com/opensearch-project/opensearch-go/v4/.gitignore new file mode 100644 index 0000000000..8c2fd150ab --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/.gitignore @@ -0,0 +1,9 @@ +tmp/ +*.test + +# editors +.idea +.vscode +bin/ + +.DS_Store \ No newline at end of file diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/.golangci.yml b/vendor/github.com/opensearch-project/opensearch-go/v4/.golangci.yml new file mode 100644 index 0000000000..7c017afb72 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/.golangci.yml @@ -0,0 +1,175 @@ +run: + timeout: 10m + modules-download-mode: readonly + +linters-settings: + errcheck: + check-blank: true + check-type-assertions: false + errorlint: + check-generated: false + default-signifies-exhaustive: false + exhaustive: + default-signifies-exhaustive: false + gci: + sections: + - standard + - default + - prefix(github.com/opensearch-project/opensearch-go) + goconst: + min-len: 3 + min-occurrences: 3 + godox: + keywords: + - BUG + - FIXME + - HACK + goimports: + local-prefixes: github.com/opensearch-project/opensearch-go + lll: + line-length: 140 + nolintlint: + allow-leading-space: false + require-explanation: true + require-specific: true + unparam: + check-exported: true + misspell: + locale: US + ignore-words: + - expect + - cancelled + prealloc: + simple: true + range-loops: true + for-loops: false + revive: + rules: + - name: exported + severity: error + disabled: false + arguments: + - "checkPrivateReceivers" + - "sayRepetitiveInsteadOfStutters" + +linters: + disable-all: true + enable: + - asasalint + - asciicheck + - bidichk + - bodyclose + - containedctx + - contextcheck + - decorder + - dogsled + - dupl + - dupword + - durationcheck + - errcheck + - errchkjson + - errname + - errorlint + - execinquery + - exhaustive + - exportloopref + - gci + - ginkgolinter + - gocheckcompilerdirectives + - gochecknoglobals + - gochecknoinits + - goconst + - gocritic + - godox + - gofmt + - gofumpt + - goheader + - goimports + - gomoddirectives + - gomodguard + - goprintffuncname + - gosec + - gosimple + - govet + - grouper + - importas + - ineffassign + - interfacebloat + - lll + - loggercheck + - makezero + - mirror + - misspell + - musttag + - nakedret + - nestif + - nilerr + - nilnil + - noctx + - nolintlint + - nonamedreturns + - nosprintfhostport + - prealloc + - predeclared + - promlinter + - reassign + - revive + - rowserrcheck + - sqlclosecheck + - staticcheck + - stylecheck + - tagalign + - testpackage + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - usestdlibvars + - wastedassign + - whitespace + - zerologlint + +issues: + include: + - EXC0012 + - EXC0014 + exclude-rules: + - path: (_test\.go|internal/) + linters: + - cyclop + - dupl + - errcheck + - gochecknoglobals + - gochecknoinits + - goconst + - noctx + - linters: + - gosec + text: "math/rand" + path: _test\.go + - linters: + - gosec + text: "TLS InsecureSkipVerify set true" + path: (_test\.go|internal/) + - linters: + - gosec + text: "G108: Profiling endpoint is automatically exposed on /debug/pprof" + path: _test\.go + - linters: + - goconst + path: opensearchapi\/api_ + - linters: + - errcheck + text: "Error return value of `debugLogger.Logf` is not checked" + - linters: + - errcheck + - gochecknoglobals + path: opensearchtransport\/logger\.go + - linters: + - nestif + path: opensearchtransport/opensearchtransport.go + - linters: + - dupl + path: (-params\.go|api_indices|api_dangling\.go|api_point_in_time\.go|rethrottle\.go|api_cat-.*\.go|plugins/security/api_\w+.go|plugins/security/api_.*-patch.go) diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/.whitesource b/vendor/github.com/opensearch-project/opensearch-go/v4/.whitesource new file mode 100644 index 0000000000..db4b0fec82 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/.whitesource @@ -0,0 +1,15 @@ +{ + "scanSettings": { + "configMode": "AUTO", + "configExternalURL": "", + "projectToken": "", + "baseBranches": [] + }, + "checkRunSettings": { + "vulnerableCheckRunConclusionLevel": "failure", + "displayMode": "diff" + }, + "issueSettings": { + "minSeverityLevel": "LOW" + } +} \ No newline at end of file diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/ADMINS.md b/vendor/github.com/opensearch-project/opensearch-go/v4/ADMINS.md new file mode 100644 index 0000000000..f9220c93b8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/ADMINS.md @@ -0,0 +1,38 @@ +- [Overview](#overview) +- [Current Admins](#current-admins) +- [Admin Responsibilities](#admin-responsibilities) + - [Prioritize Security](#prioritize-security) + - [Enforce Code of Conduct](#enforce-code-of-conduct) + - [Adopt Organizational Best Practices](#adopt-organizational-best-practices) + +## Overview + +This document explains who the admins are (see below), what they do in this repo, and how they should be doing it. If you're interested in becoming a maintainer, see [MAINTAINERS](MAINTAINERS.md). If you're interested in contributing, see [CONTRIBUTING](CONTRIBUTING.md). + +## Current Admins + +| Admin | GitHub ID | Affiliation | +| --- | --- | --- | +| Charlotte | [CEHENKLE](https://github.com/CEHENKLE) | Amazon | +| Henri Yandell | [hyandell](https://github.com/hyandell) | Amazon | +| Jack Mazanec | [jmazanec15](https://github.com/jmazanec15) | Amazon | +| Vamshi Vijay Nakkirtha | [vamshin](https://github.com/vamshin) | Amazon | +| Vijayan Balasubramanian | [VijayanB](https://github.com/VijayanB) | Amazon | + +## Admin Responsibilities + +As an admin you own stewartship of the repository and its settings. Admins have [admin-level permissions on a repository](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-permission-levels-for-an-organization). Use those privileges to serve the community and protect the repository as follows. + +### Prioritize Security + +Security is your number one priority. Manage security keys and safeguard access to the repository. + +Note that this repository is monitored and supported 24/7 by Amazon Security, see [Reporting a Vulnerability](SECURITY.md) for details. + +### Enforce Code of Conduct + +Act on [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) violations by revoking access, and blocking malicious actors. + +### Adopt Organizational Best Practices + +Adopt organizational best practices, work in the open, and collaborate with other admins by opening issues before making process changes. Prefer consistency, and avoid diverging from practices in the opensearch-project organization. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/CHANGELOG.md b/vendor/github.com/opensearch-project/opensearch-go/v4/CHANGELOG.md new file mode 100644 index 0000000000..8e14d20fd0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/CHANGELOG.md @@ -0,0 +1,345 @@ +# CHANGELOG + +Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) + +## [4.5.0] + +### Dependencies +- Bump `github.com/aws/aws-sdk-go-v2/config` from 1.29.6 to 1.29.14 ([#692](https://github.com/opensearch-project/opensearch-go/pull/692)) +- Bump `github.com/aws/aws-sdk-go` from 1.55.6 to 1.55.7 ([#696](https://github.com/opensearch-project/opensearch-go/pull/696)) +- Bump `github.com/wI2L/jsondiff` from 0.6.1 to 0.7.0 ([#700](https://github.com/opensearch-project/opensearch-go/pull/700)) + +### Added +- Adds DataStream field to IndicesGetResp struct ([#701](https://github.com/opensearch-project/opensearch-go/pull/701)) +- Adds `InnerHits` field to `SearchResp` ([#672](https://github.com/opensearch-project/opensearch-go/pull/672)) +- Adds `FilterPath` param ([#673](https://github.com/opensearch-project/opensearch-go/pull/673)) +- Adds `Aggregations` field to `MSearchResp` ([#690](https://github.com/opensearch-project/opensearch-go/pull/690)) + +### Changed +- Bump golang version to 1.22 ([#691](https://github.com/opensearch-project/opensearch-go/pull/691)) +- Change ChangeCatRecoveryItemResp Byte fields from int to string ([#691](https://github.com/opensearch-project/opensearch-go/pull/691)) +- Changed log formatted examples code ([#694](https://github.com/opensearch-project/opensearch-go/pull/694)) +- Improve the error reporting of invalid body response ([#699](https://github.com/opensearch-project/opensearch-go/pull/699)) + +### Deprecated + +### Removed + +### Fixed + +### Security + +## [4.4.0] + +### Added +- Adds `Highlight` field to `SearchHit` ([#654](https://github.com/opensearch-project/opensearch-go/pull/654)) +- Adds `MatchedQueries` field to `SearchHit` ([#663](https://github.com/opensearch-project/opensearch-go/pull/663)) +- Adds support for Opensearch 2.19 ([#668](https://github.com/opensearch-project/opensearch-go/pull/668)) + +### Changed + +### Deprecated + +### Removed + +### Fixed + +### Security + +### Dependencies +- Bump `github.com/aws/aws-sdk-go` from 1.55.5 to 1.55.6 ([#657](https://github.com/opensearch-project/opensearch-go/pull/657)) +- Bump `github.com/wI2L/jsondiff` from 0.6.0 to 0.6.1 ([#643](https://github.com/opensearch-project/opensearch-go/pull/643)) +- Bump `github.com/aws/aws-sdk-go-v2` from 1.32.2 to 1.36.1 ([#664](https://github.com/opensearch-project/opensearch-go/pull/664)) +- Bump `github.com/stretchr/testify` from 1.9.0 to 1.10.0 ([#644](https://github.com/opensearch-project/opensearch-go/pull/644)) +- Bump `github.com/aws/aws-sdk-go-v2/config` from 1.27.43 to 1.29.6 ([#665](https://github.com/opensearch-project/opensearch-go/pull/665)) + +## [4.3.0] + +### Added +- Adds ISM Alias action ([#615](https://github.com/opensearch-project/opensearch-go/pull/615)) +- Adds support for opensearch 2.17 ([#623](https://github.com/opensearch-project/opensearch-go/pull/623)) + +### Changed + +### Deprecated + +### Removed + +### Fixed +- Fix ISM Transition to omitempty Conditions field ([#609](https://github.com/opensearch-project/opensearch-go/pull/609)) +- Fix ISM Allocation field types ([#609](https://github.com/opensearch-project/opensearch-go/pull/609)) +- Fix ISM Error Notification types ([#612](https://github.com/opensearch-project/opensearch-go/pull/612)) +- Fix signer receiving drained body on retries ([#620](https://github.com/opensearch-project/opensearch-go/pull/620)) +- Fix Bulk Index Items not executing failure callbacks on bulk request failure ([#626](https://github.com/opensearch-project/opensearch-go/issues/626)) + +### Security + +### Dependencies +- Bump `github.com/aws/aws-sdk-go-v2/config` from 1.27.31 to 1.27.43 ([#611](https://github.com/opensearch-project/opensearch-go/pull/611), [#630](https://github.com/opensearch-project/opensearch-go/pull/630), [#632](https://github.com/opensearch-project/opensearch-go/pull/632)) +- Bump `github.com/aws/aws-sdk-go-v2` from 1.32.1 to 1.32.2 ([#631](https://github.com/opensearch-project/opensearch-go/pull/631)) + +## [4.2.0] + +### Dependencies +- Bump `github.com/aws/aws-sdk-go-v2/config` from 1.27.23 to 1.27.31 ([#584](https://github.com/opensearch-project/opensearch-go/pull/584), [#588](https://github.com/opensearch-project/opensearch-go/pull/588), [#593](https://github.com/opensearch-project/opensearch-go/pull/593), [#605](https://github.com/opensearch-project/opensearch-go/pull/605)) +- Bump `github.com/aws/aws-sdk-go` from 1.54.12 to 1.55.5 ([#583](https://github.com/opensearch-project/opensearch-go/pull/583), [#590](https://github.com/opensearch-project/opensearch-go/pull/590), [#595](https://github.com/opensearch-project/opensearch-go/pull/595), [#596](https://github.com/opensearch-project/opensearch-go/pull/596)) + +### Added +- Adds `Suggest` to `SearchResp` ([#602](https://github.com/opensearch-project/opensearch-go/pull/602)) +- Adds `MaxScore` to `ScrollGetResp` ([#607](https://github.com/opensearch-project/opensearch-go/pull/607)) + +### Changed +- Split SnapshotGetResp into sub structs ([#603](https://github.com/opensearch-project/opensearch-go/pull/603)) + +### Deprecated + +### Removed +- Remove workflow tests against gotip ([#604](https://github.com/opensearch-project/opensearch-go/pull/604)) + +### Fixed + +### Security + +## [4.1.0] + +### Added +- Adds the `Routing` field in SearchHit interface. ([#516](https://github.com/opensearch-project/opensearch-go/pull/516)) +- Adds the `SearchPipelines` field to `SearchParams` ([#532](https://github.com/opensearch-project/opensearch-go/pull/532)) +- Adds support for OpenSearch 2.14 ([#552](https://github.com/opensearch-project/opensearch-go/pull/552)) +- Adds the `Caches` field to Node stats ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) +- Adds the `SeqNo` and `PrimaryTerm` fields in `SearchHit` ([#574](https://github.com/opensearch-project/opensearch-go/pull/574)) +- Adds guide on configuring the client with retry and backoff ([#540](https://github.com/opensearch-project/opensearch-go/pull/540)) +- Adds OpenSearch 2.15 to compatibility workflow test ([#575](https://github.com/opensearch-project/opensearch-go/pull/575)) + +### Changed +- Security roles get response struct has its own sub structs without omitempty ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) + +### Deprecated + +### Removed + +### Fixed + +- Fixes empty request body on retry with compression enabled ([#543](https://github.com/opensearch-project/opensearch-go/pull/543)) +- Fixes `Conditions` in `PolicyStateTransition` of ISM plugin ([#556](https://github.com/opensearch-project/opensearch-go/pull/556)) +- Fixes integration test response validation when response is null ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) +- Adjust security Role struct for FLS from string to []string ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) +- Fixes wrong response parsing for indices mapping and recovery ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) +- Fixes wrong response parsing for security get requests ([#572](https://github.com/opensearch-project/opensearch-go/pull/572)) +- Fixes opensearchtransport ignores request context cancellation when `retryBackoff` is configured ([#540](https://github.com/opensearch-project/opensearch-go/pull/540)) +- Fixes opensearchtransport sleeps unexpectedly after the last retry ([#540](https://github.com/opensearch-project/opensearch-go/pull/540)) +- Improves ParseError response when server response is an unknown json ([#592](https://github.com/opensearch-project/opensearch-go/pull/592)) + +### Security + +### Dependencies +- Bump `github.com/aws/aws-sdk-go` from 1.51.21 to 1.54.12 ([#534](https://github.com/opensearch-project/opensearch-go/pull/534), [#537](https://github.com/opensearch-project/opensearch-go/pull/537), [#538](https://github.com/opensearch-project/opensearch-go/pull/538), [#545](https://github.com/opensearch-project/opensearch-go/pull/545), [#554](https://github.com/opensearch-project/opensearch-go/pull/554), [#557](https://github.com/opensearch-project/opensearch-go/pull/557), [#563](https://github.com/opensearch-project/opensearch-go/pull/563), [#564](https://github.com/opensearch-project/opensearch-go/pull/564), [#570](https://github.com/opensearch-project/opensearch-go/pull/570), [#579](https://github.com/opensearch-project/opensearch-go/pull/579)) +- Bump `github.com/wI2L/jsondiff` from 0.5.1 to 0.6.0 ([#535](https://github.com/opensearch-project/opensearch-go/pull/535), [#566](https://github.com/opensearch-project/opensearch-go/pull/566)) +- Bump `github.com/aws/aws-sdk-go-v2/config` from 1.27.11 to 1.27.23 ([#546](https://github.com/opensearch-project/opensearch-go/pull/546), [#553](https://github.com/opensearch-project/opensearch-go/pull/553), [#558](https://github.com/opensearch-project/opensearch-go/pull/558), [#562](https://github.com/opensearch-project/opensearch-go/pull/562), [#567](https://github.com/opensearch-project/opensearch-go/pull/567), [#571](https://github.com/opensearch-project/opensearch-go/pull/571), [#577](https://github.com/opensearch-project/opensearch-go/pull/577)) +- Bump `github.com/aws/aws-sdk-go-v2` from 1.27.0 to 1.30.1 ([#559](https://github.com/opensearch-project/opensearch-go/pull/559), [#578](https://github.com/opensearch-project/opensearch-go/pull/578)) + +## [4.0.0] + +### Added +- Adds GlobalIOUsage struct for nodes stats ([#506](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Adds the `Explanation` field containing the document explain details to the `SearchHit` struct. ([#504](https://github.com/opensearch-project/opensearch-go/pull/504)) +- Adds new error types ([#512](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Adds handling of non json errors to ParseError ([#512](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Adds the `Failures` field to opensearchapi structs ([#510](https://github.com/opensearch-project/opensearch-go/pull/510)) +- Adds the `Fields` field containing the document fields to the `SearchHit` struct. ([#508](https://github.com/opensearch-project/opensearch-go/pull/508)) +- Adds security plugin ([#507](https://github.com/opensearch-project/opensearch-go/pull/507)) +- Adds security settings to container for security testing ([#507](https://github.com/opensearch-project/opensearch-go/pull/507)) +- Adds cluster.get-certs to copy admin certs out of the container ([#507](https://github.com/opensearch-project/opensearch-go/pull/507)) +- Adds the `Fields` field containing stored fields to the `DocumentGetResp` struct ([#526](https://github.com/opensearch-project/opensearch-go/pull/526)) +- Adds ism plugin ([#524](https://github.com/opensearch-project/opensearch-go/pull/524)) + +### Changed +- Uses docker compose v2 instead of v1 ([#506](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Updates go version to 1.21 ([#509](https://github.com/opensearch-project/opensearch-go/pull/509)) +- Moves Error structs from opensearchapi to opensearch package ([#512](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Moves parseError function from opensearchapi to opensearch package as ParseError ([#512](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Changes ParseError function to do type assertion to determine error type ([#512](https://github.com/opensearch-project/opensearch-go/pull/506)) +- Removes unused structs and functions from opensearch ([#517](https://github.com/opensearch-project/opensearch-go/pull/517)) +- Adjusts and extent opensearch tests for better coverage ([#517](https://github.com/opensearch-project/opensearch-go/pull/517)) +- Bumps codecov action version to v4 ([#517](https://github.com/opensearch-project/opensearch-go/pull/517)) +- Changes bulk error/reason field and some cat response fields to pointer as they can be nil ([#510](https://github.com/opensearch-project/opensearch-go/pull/510)) +- Adjust workflows to work with security plugin ([#507](https://github.com/opensearch-project/opensearch-go/pull/507)) +- Updates USER_GUIDE.md and /_samples/ ([#518](https://github.com/opensearch-project/opensearch-go/pull/518)) +- Updates opensearchtransport.Client to use pooled gzip writer and buffer ([#521](https://github.com/opensearch-project/opensearch-go/pull/521)) +- Use go:build tags for testing ([#52?](https://github.com/opensearch-project/opensearch-go/pull/52?)) + +### Deprecated + +### Removed + +### Fixed +- Fixes search request missing a slash when no indices are given ([#470](https://github.com/opensearch-project/opensearch-go/pull/469)) +- Fixes opensearchtransport check for nil response body ([#517](https://github.com/opensearch-project/opensearch-go/pull/517)) + +### Security + +### Dependencies +- Bumps `github.com/aws/aws-sdk-go-v2` from 1.25.3 to 1.26.1 +- Bumps `github.com/wI2L/jsondiff` from 0.4.0 to 0.5.1 +- Bumps `github.com/aws/aws-sdk-go` from 1.50.36 to 1.51.21 +- Bumps `github.com/aws/aws-sdk-go-v2/config` from 1.27.7 to 1.27.11 + +## [3.1.0] + +### Added + +- Adds new struct fields introduced in OpenSearch 2.12 ([#482](https://github.com/opensearch-project/opensearch-go/pull/482)) +- Adds initial admin password environment variable and CI changes to support 2.12.0 release ([#449](https://github.com/opensearch-project/opensearch-go/pull/449)) +- Adds `merge_id` field for indices segment request ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) + +### Changed + +- Updates workflow action versions ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) +- Changes integration tests to work with secure and unsecure OpenSearch ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) +- Moves functions from `opensearch/internal/test` to `internal/test` for more general test uses ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) +- Changes `custom_foldername` field to pointer as it can be `null` ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) +- Changs cat indices Primary and Replica field to pointer as it can be `null` ([#488](https://github.com/opensearch-project/opensearch-go/pull/488)) +- Replaces `ioutil` with `io` in examples and integration tests [#495](https://github.com/opensearch-project/opensearch-go/pull/495) + +### Fixed + +- Fix incorrect SigV4 `x-amz-content-sha256` with AWS SDK v1 requests without a body ([#496](https://github.com/opensearch-project/opensearch-go/pull/496)) + +### Dependencies + +- Bumps `github.com/aws/aws-sdk-go` from 1.48.13 to 1.50.36 +- Bumps `github.com/aws/aws-sdk-go-v2/config` from 1.25.11 to 1.27.7 +- Bumps `github.com/stretchr/testify` from 1.8.4 to 1.9.0 + +## [3.0.0] + +### Added + +- Adds `Err()` function to Response for detailed errors ([#246](https://github.com/opensearch-project/opensearch-go/pull/246)) +- Adds golangci-lint as code analysis tool ([#313](https://github.com/opensearch-project/opensearch-go/pull/313)) +- Adds govulncheck to check for go vulnerablities ([#405](https://github.com/opensearch-project/opensearch-go/pull/405)) +- Adds opensearchapi with new client and function structure ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Adds integration tests for all opensearchapi functions ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Adds guide on making raw JSON REST requests ([#399](https://github.com/opensearch-project/opensearch-go/pull/399)) +- Adds IPV6 support in the DiscoverNodes method ([#458](https://github.com/opensearch-project/opensearch-go/issues/458)) + +### Changed + +- Removes the need for double error checking ([#246](https://github.com/opensearch-project/opensearch-go/pull/246)) +- Updates and adjusted golangci-lint, solve linting complains for signer ([#352](https://github.com/opensearch-project/opensearch-go/pull/352)) +- Solves linting complains for opensearchtransport ([#353](https://github.com/opensearch-project/opensearch-go/pull/353)) +- Updates Developer guide to include docker build instructions ([#385](https://github.com/opensearch-project/opensearch-go/pull/385)) +- Tests against version 2.9.0, 2.10.0, run tests in all branches, changes integration tests to wait for OpenSearch to start ([#392](https://github.com/opensearch-project/opensearch-go/pull/392)) +- Makefile: uses docker golangci-lint, run integration test on `.` folder, change coverage generation ([#392](https://github.com/opensearch-project/opensearch-go/pull/392)) +- golangci-lint: updates rules and fail when issues are found ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- go: updates to golang version 1.20 ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- guids: updates to work for the new opensearchapi ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Adjusts tests to new opensearchapi functions and structs ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Changes codecov to comment code coverage to each PR ([#410](https://github.com/opensearch-project/opensearch-go/pull/410)) +- Changes module version from v2 to v3 ([#444](https://github.com/opensearch-project/opensearch-go/pull/444)) +- Handle unexpected non-json errors with the response body ([#523](https://github.com/opensearch-project/opensearch-go/pull/523)) + +### Deprecated + +- Deprecates legacy API `/_template` ([#390](https://github.com/opensearch-project/opensearch-go/pull/390)) + +### Removed + +- Removes all old opensearchapi functions ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Removes `/internal/build` code and folders ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) + +### Fixed + +- Corrects AWSv4 signature on DataStream `Stats` with no index name specified ([#338](https://github.com/opensearch-project/opensearch-go/pull/338)) +- Fixes GetSourceRequest `Source` field and deprecated the `Source` parameter ([#402](https://github.com/opensearch-project/opensearch-go/pull/402)) +- Corrects developer guide summary with golang version 1.20 ([#434](https://github.com/opensearch-project/opensearch-go/pull/434)) + +### Dependencies + +- Bumps `github.com/aws/aws-sdk-go` from 1.44.263 to 1.48.13 +- Bumps `github.com/aws/aws-sdk-go-v2` from 1.18.0 to 1.23.5 +- Bumps `github.com/aws/aws-sdk-go-v2/config` from 1.18.25 to 1.25.11 +- Bumps `github.com/stretchr/testify` from 1.8.2 to 1.8.4 +- Bumps `golang.org/x/net` from 0.7.0 to 0.17.0 +- Bumps `github.com/golangci/golangci-lint-action` from 1.53.3 to 1.54.2 + +## [2.3.0] + +### Added + +- Adds implementation of Data Streams API ([#257](https://github.com/opensearch-project/opensearch-go/pull/257)) +- Adds Point In Time API ([#253](https://github.com/opensearch-project/opensearch-go/pull/253)) +- Adds InfoResp type ([#253](https://github.com/opensearch-project/opensearch-go/pull/253)) +- Adds markdown linter ([#261](https://github.com/opensearch-project/opensearch-go/pull/261)) +- Adds testcases to check upsert functionality ([#269](https://github.com/opensearch-project/opensearch-go/pull/269)) +- Adds @Jakob3xD to co-maintainers ([#270](https://github.com/opensearch-project/opensearch-go/pull/270)) +- Adds dynamic type to \_source field ([#285](https://github.com/opensearch-project/opensearch-go/pull/285)) +- Adds testcases for Document API ([#285](https://github.com/opensearch-project/opensearch-go/pull/285)) +- Adds `index_lifecycle` guide ([#287](https://github.com/opensearch-project/opensearch-go/pull/287)) +- Adds `bulk` guide ([#292](https://github.com/opensearch-project/opensearch-go/pull/292)) +- Adds `search` guide ([#291](https://github.com/opensearch-project/opensearch-go/pull/291)) +- Adds `document_lifecycle` guide ([#290](https://github.com/opensearch-project/opensearch-go/pull/290)) +- Adds `index_template` guide ([#289](https://github.com/opensearch-project/opensearch-go/pull/289)) +- Adds `advanced_index_actions` guide ([#288](https://github.com/opensearch-project/opensearch-go/pull/288)) +- Adds testcases to check UpdateByQuery functionality ([#304](https://github.com/opensearch-project/opensearch-go/pull/304)) +- Adds additional timeout after cluster start ([#303](https://github.com/opensearch-project/opensearch-go/pull/303)) +- Adds docker healthcheck to auto restart the container ([#315](https://github.com/opensearch-project/opensearch-go/pull/315)) + +### Changed + +- Uses `[]string` instead of `string` in `SnapshotDeleteRequest` ([#237](https://github.com/opensearch-project/opensearch-go/pull/237)) +- Updates workflows to reduce CI time, consolidate OpenSearch versions, update compatibility matrix ([#242](https://github.com/opensearch-project/opensearch-go/pull/242)) +- Moves @svencowart to emeritus maintainers ([#270](https://github.com/opensearch-project/opensearch-go/pull/270)) +- Reads, closes and replaces the http Reponse Body ([#300](https://github.com/opensearch-project/opensearch-go/pull/300)) + +### Fixed + +- Corrects curl logging to emit the correct URL destination ([#101](https://github.com/opensearch-project/opensearch-go/pull/101)) + +### Dependencies + +- Bumps `github.com/aws/aws-sdk-go` from 1.44.180 to 1.44.263 +- Bumps `github.com/aws/aws-sdk-go-v2` from 1.17.4 to 1.18.0 +- Bumps `github.com/aws/aws-sdk-go-v2/config` from 1.18.8 to 1.18.25 +- Bumps `github.com/stretchr/testify` from 1.8.1 to 1.8.2 + +## [2.2.0] + +### Added + +- Adds Github workflow for changelog verification ([#172](https://github.com/opensearch-project/opensearch-go/pull/172)) +- Adds Go Documentation link for the client ([#182](https://github.com/opensearch-project/opensearch-go/pull/182)) +- Adds support for Amazon OpenSearch Serverless ([#216](https://github.com/opensearch-project/opensearch-go/pull/216)) + +### Removed + +- Removes info call before performing every request ([#219](https://github.com/opensearch-project/opensearch-go/pull/219)) + +### Fixed + +- Renames the sequence number struct tag to if_seq_no to fix optimistic concurrency control ([#166](https://github.com/opensearch-project/opensearch-go/pull/166)) +- Fixes `RetryOnConflict` on bulk indexer ([#215](https://github.com/opensearch-project/opensearch-go/pull/215)) + +### Dependencies + +- Bumps `github.com/aws/aws-sdk-go-v2` from 1.17.1 to 1.17.3 +- Bumps `github.com/aws/aws-sdk-go-v2/config` from 1.17.10 to 1.18.8 +- Bumps `github.com/aws/aws-sdk-go` from 1.44.176 to 1.44.180 +- Bumps `github.com/aws/aws-sdk-go` from 1.44.132 to 1.44.180 +- Bumps `github.com/stretchr/testify` from 1.8.0 to 1.8.1 +- Bumps `github.com/aws/aws-sdk-go` from 1.44.45 to 1.44.132 + +[4.5.0]: https://github.com/opensearch-project/opensearch-go/compare/v4.4.0...v4.5.0 +[4.4.0]: https://github.com/opensearch-project/opensearch-go/compare/v4.3.0...v4.4.0 +[4.3.0]: https://github.com/opensearch-project/opensearch-go/compare/v4.2.0...v4.3.0 +[4.2.0]: https://github.com/opensearch-project/opensearch-go/compare/v4.1.0...v4.2.0 +[4.1.0]: https://github.com/opensearch-project/opensearch-go/compare/v4.0.0...v4.1.0 +[4.0.0]: https://github.com/opensearch-project/opensearch-go/compare/v3.1.0...v4.0.0 +[3.1.0]: https://github.com/opensearch-project/opensearch-go/compare/v3.0.0...v3.1.0 +[3.0.0]: https://github.com/opensearch-project/opensearch-go/compare/v2.3.0...v3.0.0 +[2.3.0]: https://github.com/opensearch-project/opensearch-go/compare/v2.2.0...v2.3.0 +[2.2.0]: https://github.com/opensearch-project/opensearch-go/compare/v2.1.0...v2.2.0 +[2.1.0]: https://github.com/opensearch-project/opensearch-go/compare/v2.0.1...v2.1.0 +[2.0.1]: https://github.com/opensearch-project/opensearch-go/compare/v2.0.0...v2.0.1 +[2.0.0]: https://github.com/opensearch-project/opensearch-go/compare/v1.1.0...v2.0.0 +[1.0.0]: https://github.com/opensearch-project/opensearch-go/compare/v1.0.0...v1.1.0 diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/CODE_OF_CONDUCT.md b/vendor/github.com/opensearch-project/opensearch-go/v4/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..c5efd05f7c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/CODE_OF_CONDUCT.md @@ -0,0 +1,22 @@ +This code of conduct applies to all spaces provided by the OpenSource project including in code, documentation, issue trackers, mailing lists, chat channels, wikis, blogs, social media and any other communication channels used by the project. + +**Our open source communities endeavor to:** + +- Be Inclusive: We are committed to being a community where everyone can join and contribute. This means using inclusive and welcoming language. +- Be Welcoming: We are committed to maintaining a safe space for everyone to be able to contribute. +- Be Respectful: We are committed to encouraging differing viewpoints, accepting constructive criticism and work collaboratively towards decisions that help the project grow. Disrespectful and unacceptable behavior will not be tolerated. +- Be Collaborative: We are committed to supporting what is best for our community and users. When we build anything for the benefit of the project, we should document the work we do and communicate to others on how this affects their work. + +**Our Responsibility. As contributors, members, or bystanders we each individually have the responsibility to behave professionally and respectfully at all times. Disrespectful and unacceptable behaviors include, but are not limited to:** + +- The use of violent threats, abusive, discriminatory, or derogatory language; +- Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, race, political or religious affiliation; +- Posting of sexually explicit or violent content; +- The use of sexualized language and unwelcome sexual attention or advances; +- Public or private harassment of any kind; +- Publishing private information, such as physical or electronic address, without permission; +- Other conduct which could reasonably be considered inappropriate in a professional setting; +- Advocating for or encouraging any of the above behaviors. +- Enforcement and Reporting Code of Conduct Issues: + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported. [Contact us](mailto:opensource-codeofconduct@amazon.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/COMPATIBILITY.md b/vendor/github.com/opensearch-project/opensearch-go/v4/COMPATIBILITY.md new file mode 100644 index 0000000000..8fe1797a83 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/COMPATIBILITY.md @@ -0,0 +1,15 @@ +- [Compatibility with OpenSearch](#compatibility-with-opensearch) +- [Upgrading](#upgrading) + +## Compatibility with OpenSearch + +The below matrix shows the compatibility of the [`opensearch-go`](https://pkg.go.dev/github.com/opensearch-project/opensearch-go) with versions of [`OpenSearch`](https://opensearch.org/downloads.html#opensearch). + +| Client Version | OpenSearch Version | +| -------------- | ------------------ | +| 1.x.0 | 1.x | +| 2.x.0 | 1.3.13-2.11.0 | + +## Upgrading + +Major versions of OpenSearch introduce breaking changes that require careful upgrades of the client. While `opensearch-go-client` 2.0.0 works against the latest OpenSearch 1.x, certain deprecated features removed in OpenSearch 2.0 have also been removed from the client. Please refer to the [OpenSearch documentation](https://opensearch.org/docs/latest/clients/index/) for more information. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/CONTRIBUTING.md b/vendor/github.com/opensearch-project/opensearch-go/v4/CONTRIBUTING.md new file mode 100644 index 0000000000..e7b0764fd4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/CONTRIBUTING.md @@ -0,0 +1,113 @@ +- [Contributing to OpenSearch](#contributing-to-opensearch) +- [First Things First](#first-things-first) +- [Ways to Contribute](#ways-to-contribute) + - [Bug Reports](#bug-reports) + - [Feature Requests](#feature-requests) + - [Contributing Code](#contributing-code) +- [Developer Certificate of Origin](#developer-certificate-of-origin) +- [Changelog](#changelog) + - [Adding Changes](#adding-changes) +- [Review Process](#review-process) + +## Contributing to OpenSearch + +OpenSearch is a community project that is built and maintained by people just like **you**. We're glad you're interested in helping out. There are several different ways you can do it, but before we talk about that, let's talk about how to get started. + +## First Things First + +1. **When in doubt, open an issue** - For almost any type of contribution, the first step is opening an issue. Even if you think you already know what the solution is, writing down a description of the problem you're trying to solve will help everyone get context when they review your pull request. If it's truly a trivial change (e.g. spelling error), you can skip this step -- but as the subject says, when it doubt, [open an issue](https://github.com/opensearch-project/opensearch-go/issues/new/choose). + +2. **Only submit your own work** (or work you have sufficient rights to submit) - Please make sure that any code or documentation you submit is your work or you have the rights to submit. We respect the intellectual property rights of others, and as part of contributing, we'll ask you to sign your contribution with a "Developer Certificate of Origin" (DCO) that states you have the rights to submit this work and you understand we'll use your contribution. There's more information about this topic in the [DCO section](#developer-certificate-of-origin). + +## Ways to Contribute + +### Bug Reports + +Ugh! Bugs! + +A bug is when software behaves in a way that you didn't expect and the developer didn't intend. To help us understand what's going on, we first want to make sure you're working from the latest version. + +Once you've confirmed that the bug still exists in the latest version, you'll want to check to make sure it's not something we already know about on the [open issues GitHub page](https://github.com/opensearch-project/opensearch-go/issues/new/choose). + +If you've upgraded to the latest version and you can't find it in our open issues list, then you'll need to tell us how to reproduce it Provide as much information as you can. You may think that the problem lies with your query, when actually it depends on how your data is indexed. The easier it is for us to recreate your problem, the faster it is likely to be fixed. + +### Feature Requests + +If you've thought of a way that OpenSearch could be better, we want to hear about it. We track feature requests using GitHub, so please feel free to open an issue which describes the feature you would like to see, why you need it, and how it should work. + +### Contributing Code + +As with other types of contributions, the first step is to [open an issue on GitHub](https://github.com/opensearch-project/opensearch-go/issues/new/choose). Opening an issue before you make changes makes sure that someone else isn't already working on that particular problem. It also lets us all work together to find the right approach before you spend a bunch of time on a PR. So again, when in doubt, open an issue. + +## Developer Certificate of Origin + +OpenSearch is an open source product released under the Apache 2.0 license (see either [the Apache site](https://www.apache.org/licenses/LICENSE-2.0) or the [LICENSE.txt file](LICENSE.txt)). The Apache 2.0 license allows you to freely use, modify, distribute, and sell your own products that include Apache 2.0 licensed software. + +We respect intellectual property rights of others and we want to make sure all incoming contributions are correctly attributed and licensed. A Developer Certificate of Origin (DCO) is a lightweight mechanism to do that. + +The DCO is a declaration attached to every contribution made by every developer. In the commit message of the contribution, the developer simply adds a `Signed-off-by` statement and thereby agrees to the DCO, which you can find below or at [DeveloperCertificate.org](http://developercertificate.org/). + +``` +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the + best of my knowledge, is covered under an appropriate open + source license and I have the right under that license to + submit that work with modifications, whether created in whole + or in part by me, under the same open source license (unless + I am permitted to submit under a different license), as + Indicated in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including + all personal information I submit with it, including my + sign-off) is maintained indefinitely and may be redistributed + consistent with this project or the open source license(s) + involved. +``` + +We require that every contribution to OpenSearch is signed with a Developer Certificate of Origin. Additionally, please use your real name. We do not accept anonymous contributors nor those utilizing pseudonyms. + +Each commit must include a DCO which looks like this + +``` +Signed-off-by: Jane Smith +``` + +You may type this line on your own when writing your commit messages. However, if your user.name and user.email are set in your git configs, you can use `-s` or `– – signoff` to add the `Signed-off-by` line to the end of the commit message. + +## Changelog + +OpenSearch-go maintains a version specific changelog by enforcing a change to the ongoing [CHANGELOG](CHANGELOG.md) file adhering to the [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) format. + +The changes are curated by version, with the changes to the main branch added chronologically to the `Unreleased` version. Each version has corresponding sections which list out the category of the change - `Added`, `Changed`, `Deprecated`, `Removed`, `Fixed`, `Security`. + +### Adding Changes + +As a contributor, you must ensure that every pull request has its changes listed out within the corresponding version and appropriate section of the [CHANGELOG](CHANGELOG.md) file. + +Adding in the change is a two step process - + +1. Add your changes to the corresponding section within the CHANGELOG file with dummy pull request information, publish the PR. + +2. Update the entry for your change in [`CHANGELOG.md`](CHANGELOG.md) and make sure that you reference the pull request there. + +## Review Process + +We deeply appreciate everyone who takes the time to make a contribution. We will review all contributions as quickly as possible. As a reminder, [opening an issue](https://github.com/opensearch-project/opensearch-go/issues/new/choose) discussing your change before you make it is the best way to smooth the PR process. This will prevent a rejection because someone else is already working on the problem, or because the solution is incompatible with the architectural direction. + +During the PR process, expect that there will be some back-and-forth. Please try to respond to comments in a timely fashion, and if you don't wish to continue with the PR, let us know. If a PR takes too many iterations for its complexity or size, we may reject it. Additionally, if you stop responding we may close the PR as abandoned. In either case, if you feel this was done in error, please add a comment on the PR. + +If we accept the PR, a [maintainer](MAINTAINERS.md) will merge your change and usually take care of backporting it to appropriate branches ourselves. + +If we reject the PR, we will close the pull request with a comment explaining why. This decision isn't always final: if you feel we have misunderstood your intended change or otherwise think that we should reconsider then please continue the conversation with a comment on the PR and we'll do our best to address any further points you raise. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/DEVELOPER_GUIDE.md b/vendor/github.com/opensearch-project/opensearch-go/v4/DEVELOPER_GUIDE.md new file mode 100644 index 0000000000..e89c7f3d3b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/DEVELOPER_GUIDE.md @@ -0,0 +1,147 @@ +- [Developer Guide](#developer-guide) + - [Getting Started](#getting-started) + - [Git Clone OpenSearch Go Client Repository](#git-clone-opensearch-go-client-repository) + - [Install Prerequisites](#install-prerequisites) + - [Go 1.21](#go-121) + - [Docker](#docker) + - [Windows](#windows) + - [Unit Testing](#unit-testing) + - [Integration Testing](#integration-testing) + - [Composing an OpenSearch Docker Container](#composing-an-opensearch-docker-container) + - [Execute integration tests from your terminal](#execute-integration-tests-from-your-terminal) + - [Lint](#lint) + - [Markdown lint](#markdown-lint) + - [Go lint](#go-lint) + - [Coverage](#coverage) + - [Use an Editor](#use-an-editor) + - [GoLand](#goland) + - [Vim](#vim) + +# Developer Guide + +So you want to contribute code to the OpenSearch Go Client? Excellent! We're glad you're here. Here's what you need to do: + +## Getting Started + +### Git Clone OpenSearch Go Client Repository + +Fork [opensearch-project/opensearch-go](https://github.com/opensearch-project/opensearch-go) and clone locally, e.g. `git clone https://github.com/[your username]/opensearch-go.git`. + +### Install Prerequisites + +#### Go 1.21 + +OpenSearch Go Client builds using [Go](https://go.dev/doc/install) 1.21 at a minimum. + +#### Docker + +[Docker](https://docs.docker.com/get-docker/) is required for building some OpenSearch artifacts and executing integration tests. + +#### Windows + +To build the project on Windows, use [WSL2](https://learn.microsoft.com/en-us/windows/wsl/install), the compatibility layer for running Linux applications. + +Install `make` +``` +sudo apt install make +``` + +### Unit Testing + +Go has a simple tool for running tests, and we simplified it further by creating this make command: + +``` +make test-unit +``` + +Individual unit tests can be run with the following command: + +``` +cd folder-path/to/test; +go test -v -run TestName; +``` + +### Integration Testing + +In order to test opensearch-go client, you need a running OpenSearch cluster. You can use Docker to accomplish this. The [Docker Compose file](.ci/opensearch/docker-compose.yml) supports the ability to run integration tests for the project in local environments. If you have not installed docker-compose, you can install it from this [link](https://docs.docker.com/compose/install/). + +### Composing an OpenSearch Docker Container + +Ensure that Docker is installed on your local machine. You can check by running `docker --version`. Next, navigate to your local opensearch-go repository. Run the following command to build and start the OpenSearch docker container. + +``` +make cluster.build cluster.start +``` + +This command will start the OpenSearch container using the `docker-compose.yaml` configuration file. During the build process, the necessary dependencies and files will be downloaded, which may take some time depending on your internet connection and system resources. + +Once the container is built and running, you can open a web browser and navigate to localhost:9200 to access the OpenSearch docker container. + +In order to differentiate unit tests from integration tests, Go has a built-in mechanism for allowing you to logically separate your tests with [build tags](https://pkg.go.dev/cmd/go#hdr-Build_constraints). The build tag needs to be placed as close to the top of the file as possible, and must have a blank line beneath it. Hence, create all integration tests with build tag 'integration'. + +#### Execute integration tests from your terminal + +1. Run below command to start containers. By default, it will launch latest OpenSearch cluster. + ``` + make cluster.build cluster.start + ``` +2. Run all integration tests. + ``` + make test-integ race=true + ``` +3. Stop and clean containers. + ``` + make cluster.stop cluster.clean + ``` + +## Lint + +To keep all the code in a certain uniform format, it was decided to use some writing rules. If you wrote something wrong, it's okay, you can simply run the script to check the necessary files, and optionally format the content. But keep in mind that all these checks are repeated on the pipeline, so it's better to check locally. + +### Markdown lint + +To check the markdown files, run the following command: + +``` +make lint.markdown +``` + +### Go lint + +To check all go files, run the following command: + +``` +make linters +``` + +## Coverage + +To get the repository test coverage, run the following command: + +For the results to be display in your terminal: + +``` +make coverage +``` + +For the results to be display in your browser: + +``` +make coverage-html +``` + +## Use an Editor + +### GoLand + +You can import the OpenSearch project into GoLand as follows: + +1. Select **File | Open** +2. In the subsequent dialog navigate to the ~/go/src/opensearch-go and click **Open** + +After you have opened your project, you need to specify the location of the Go SDK. You can either specify a local path to the SDK or download it. To set the Go SDK, navigate to **Go | GOROOT** and set accordingly. + +### Vim + +To improve your vim experience with Go, you might want to check out [fatih/vim-go](https://github.com/fatih/vim-go). +For example it correctly formats the file and validates it on save. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/LICENSE.txt b/vendor/github.com/opensearch-project/opensearch-go/v4/LICENSE.txt new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/MAINTAINERS.md b/vendor/github.com/opensearch-project/opensearch-go/v4/MAINTAINERS.md new file mode 100644 index 0000000000..6244090287 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/MAINTAINERS.md @@ -0,0 +1,21 @@ +## Overview + +This document contains a list of maintainers in this repo. See [opensearch-project/.github/RESPONSIBILITIES.md](https://github.com/opensearch-project/.github/blob/main/RESPONSIBILITIES.md#maintainer-responsibilities) that explains what the role of maintainer means, what maintainers do in this and other repos, and how they should be doing it. If you're interested in contributing, and becoming a maintainer, see [CONTRIBUTING](CONTRIBUTING.md). + +## Current Maintainers + +| Maintainer | GitHub ID | Affiliation | +| ----------------------- | ----------------------------------------- | ------------------- | +| Daniel Doubrovkine | [dblock](https://github.com/dblock) | Independent | +| Jakob Hahn | [Jakob3xD](https://github.com/Jakob3xD) | Hetzner Online GmbH | +| Vacha Shah | [VachaShah](https://github.com/VachaShah) | Amazon | +| Vijayan Balasubramanian | [VijayanB](https://github.com/VijayanB) | Amazon | + +## Emeritus + +| Maintainer | GitHub ID | Affiliation | +| ---------------------- | ------------------------------------------- | ----------- | +| Jack Mazanec | [jmazanec15](https://github.com/jmazanec15) | Amazon | +| Rob Cowart | [robcowart](https://github.com/robcowart) | ElastiFlow | +| Sven Cowart | [svencowart](https://github.com/svencowart) | | +| Vamshi Vijay Nakkirtha | [vamshin](https://github.com/vamshin) | Amazon | diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/Makefile b/vendor/github.com/opensearch-project/opensearch-go/v4/Makefile new file mode 100644 index 0000000000..a2d823c931 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/Makefile @@ -0,0 +1,258 @@ +SHELL := /bin/bash + +##@ Format project using goimports tool +format: + goimports -w .; + +##@ Test +test-unit: ## Run unit tests + @printf "\033[2m→ Running unit tests...\033[0m\n" +ifdef race + $(eval testunitargs += "-race") +endif + $(eval testunitargs += "-cover" "./..." "-args" "-test.gocoverdir=$(PWD)/tmp/unit") + @mkdir -p $(PWD)/tmp/unit + @echo "go test -v" $(testunitargs); \ + go test -v $(testunitargs); +ifdef coverage + @go tool covdata textfmt -i=$(PWD)/tmp/unit -o $(PWD)/tmp/unit.cov +endif +test: test-unit + +test-integ: ## Run integration tests + @printf "\033[2m→ Running integration tests...\033[0m\n" + $(eval testintegtags += "integration,core,plugins") +ifdef multinode + $(eval testintegtags += "multinode") +endif +ifdef race + $(eval testintegargs += "-race") +endif + $(eval testintegargs += "-cover" "-tags=$(testintegtags)" "-timeout=1h" "./..." "-args" "-test.gocoverdir=$(PWD)/tmp/integration") + @mkdir -p $(PWD)/tmp/integration + @echo "go test -v" $(testintegargs); \ + go test -v $(testintegargs); +ifdef coverage + @go tool covdata textfmt -i=$(PWD)/tmp/integration -o $(PWD)/tmp/integ.cov +endif + +test-integ-core: ## Run base integration tests + @make test-integ testintegtags=integration,core + +test-integ-plugins: ## Run plugin integration tests + @make test-integ testintegtags=integration,plugins + +test-integ-secure: ##Run secure integration tests + @SECURE_INTEGRATION=true make test-integ + +test-integ-core-secure: ## Run secure base integration tests + @SECURE_INTEGRATION=true make test-integ testintegtags=integration,core + +test-integ-plugins-secure: ## Run secure plugin integration tests + @SECURE_INTEGRATION=true make test-integ testintegtags=integration,plugins + + +test-bench: ## Run benchmarks + @printf "\033[2m→ Running benchmarks...\033[0m\n" + go test -run=none -bench=. -benchmem ./... + +coverage: ## Print test coverage report + @make gen-coverage + @go tool cover -func=$(PWD)/tmp/total.cov + @printf "\033[0m--------------------------------------------------------------------------------\n\033[0m" + +coverage-html: ## Open test coverage report in browser + @make gen-coverage + @go tool cover -html $(PWD)/tmp/total.cov + +gen-coverage: ## Generate test coverage report + @printf "\033[2m→ Generating test coverage report...\033[0m\n" + @rm -rf tmp + @mkdir tmp + @mkdir tmp/unit + @mkdir tmp/integration + @make test-unit coverage=true + @make test-integ coverage=true + @make build-coverage + +build-coverage: + @go tool covdata textfmt -i=$(PWD)/tmp/unit,$(PWD)/tmp/integration -o $(PWD)/tmp/total.cov + +##@ Development +lint: ## Run lint on the package + @printf "\033[2m→ Running lint...\033[0m\n" + go vet github.com/opensearch-project/opensearch-go/... + go list github.com/opensearch-project/opensearch-go/... | 'grep' -v internal | xargs golint -set_exit_status + +package := "prettier" +lint.markdown: + @printf "\033[2m→ Checking node installed...\033[0m\n" + if type node > /dev/null 2>&1 && which node > /dev/null 2>&1 ; then \ + node -v; \ + echo -e "\033[33m Node is installed, continue...\033[0m\n"; \ + else \ + echo -e "\033[31m Please install node\033[0m\n"; \ + exit 1; \ + fi + @printf "\033[2m→ Checking npm installed...\033[0m\n" + if type npm > /dev/null 2>&1 && which npm > /dev/null 2>&1 ; then \ + npm -v; \ + echo -e "\033[33m NPM is installed, continue...\033[0m\n"; \ + else \ + echo -e "\033[31m Please install npm\033[0m\n"; \ + exit 1; \ + fi + @printf "\033[2m→ Checking $(package) installed...\033[0m\n" + if [ `npm list -g | grep -c $(package)` -eq 0 -o ! -d node_module ]; then \ + echo -e "\033[33m Installing $(package)...\033[0m"; \ + npm install -g $(package) --no-shrinkwrap; \ + fi + @printf "\033[2m→ Running markdown lint...\033[0m\n" + if npx $(package) --prose-wrap never --check **/*.md; [[ $$? -ne 0 ]]; then \ + echo -e "\033[32m→ Found invalid files. Want to auto-format invalid files? (y/n) \033[0m"; \ + read RESP; \ + if [[ $$RESP = "y" || $$RESP = "Y" ]]; then \ + echo -e "\033[33m Formatting...\033[0m"; \ + npx $(package) --prose-wrap never --write **/*.md; \ + echo -e "\033[34m \nAll invalid files are formatted\033[0m"; \ + else \ + echo -e "\033[33m Unfortunately you are cancelled auto fixing. But we will definitely fix it in the pipeline\033[0m"; \ + fi \ + fi + + +backport: ## Backport one or more commits from main into version branches +ifeq ($(origin commits), undefined) + @echo "Missing commit(s), exiting..." + @exit 2 +endif +ifndef branches + $(eval branches_list = '1.x') +else + $(eval branches_list = $(shell echo $(branches) | tr ',' ' ') ) +endif + $(eval commits_list = $(shell echo $(commits) | tr ',' ' ')) + @printf "\033[2m→ Backporting commits [$(commits)]\033[0m\n" + @{ \ + set -e -o pipefail; \ + for commit in $(commits_list); do \ + git show --pretty='%h | %s' --no-patch $$commit; \ + done; \ + echo ""; \ + for branch in $(branches_list); do \ + printf "\033[2m→ $$branch\033[0m\n"; \ + git checkout $$branch; \ + for commit in $(commits_list); do \ + git cherry-pick -x $$commit; \ + done; \ + git status --short --branch; \ + echo ""; \ + done; \ + printf "\033[2m→ Push updates to Github:\033[0m\n"; \ + for branch in $(branches_list); do \ + echo "git push --verbose origin $$branch"; \ + done; \ + } + +release: ## Release a new version to Github + $(eval branch = $(shell git rev-parse --abbrev-ref HEAD)) + $(eval current_version = $(shell cat internal/version/version.go | sed -Ee 's/const Client = "(.*)"/\1/' | tail -1)) + @printf "\033[2m→ [$(branch)] Current version: $(current_version)...\033[0m\n" +ifndef version + @printf "\033[31m[!] Missing version argument, exiting...\033[0m\n" + @exit 2 +endif +ifeq ($(version), "") + @printf "\033[31m[!] Empty version argument, exiting...\033[0m\n" + @exit 2 +endif + @printf "\033[2m→ [$(branch)] Creating version $(version)...\033[0m\n" + @{ \ + set -e -o pipefail; \ + cp internal/version/version.go internal/version/version.go.OLD && \ + cat internal/version/version.go.OLD | sed -e 's/Client = ".*"/Client = "$(version)"/' > internal/version/version.go && \ + go vet internal/version/version.go && \ + go fmt internal/version/version.go && \ + git diff --color-words internal/version/version.go | tail -n 1; \ + } + @{ \ + set -e -o pipefail; \ + printf "\033[2m→ Commit and create Git tag? (y/n): \033[0m\c"; \ + read continue; \ + if [[ $$continue == "y" ]]; then \ + git add internal/version/version.go && \ + git commit --no-status --quiet --message "Release $(version)" && \ + git tag --annotate v$(version) --message 'Release $(version)'; \ + printf "\033[2m→ Push `git show --pretty='%h (%s)' --no-patch HEAD` to Github:\033[0m\n\n"; \ + printf "\033[1m git push origin HEAD && git push origin v$(version)\033[0m\n\n"; \ + mv internal/version/version.go.OLD internal/version/version.go && \ + git add internal/version/version.go && \ + original_version=`cat internal/version/version.go | sed -ne 's;^const Client = "\(.*\)"$$;\1;p'` && \ + git commit --no-status --quiet --message "Update version to $$original_version"; \ + printf "\033[2m→ Version updated to [$$original_version].\033[0m\n\n"; \ + else \ + echo "Aborting..."; \ + rm internal/version/version.go.OLD; \ + exit 1; \ + fi; \ + } + +godoc: ## Display documentation for the package + @printf "\033[2m→ Generating documentation...\033[0m\n" + @echo "* http://localhost:6060/pkg/github.com/opensearch-project/opensearch-go" + @echo "* http://localhost:6060/pkg/github.com/opensearch-project/opensearch-go/opensearchapi" + @echo "* http://localhost:6060/pkg/github.com/opensearch-project/opensearch-go/opensearchtransport" + @echo "* http://localhost:6060/pkg/github.com/opensearch-project/opensearch-go/opensearchutil" + @printf "\n" + godoc --http=localhost:6060 --play + +cluster.build: + docker compose --project-directory .ci/opensearch build --pull; + +cluster.start: + docker compose --project-directory .ci/opensearch up -d; + +cluster.stop: + docker compose --project-directory .ci/opensearch down; + +cluster.get-cert: + @if [[ -v SECURE_INTEGRATION ]] && [[ $$SECURE_INTEGRATION == "true" ]]; then \ + docker cp $$(docker compose --project-directory .ci/opensearch ps --format '{{.Name}}'):/usr/share/opensearch/config/kirk.pem admin.pem && \ + docker cp $$(docker compose --project-directory .ci/opensearch ps --format '{{.Name}}'):/usr/share/opensearch/config/kirk-key.pem admin.key; \ + fi + + +cluster.clean: ## Remove unused Docker volumes and networks + @printf "\033[2m→ Cleaning up Docker assets...\033[0m\n" + docker volume prune --force + docker network prune --force + docker system prune --volumes --force + +linters: + docker run -t --rm -v $$(pwd):/app -v ~/.cache/golangci-lint/v1.54.2:/root/.cache -w /app golangci/golangci-lint:v1.54.2 golangci-lint run --timeout=5m + +workflow: ## Run all github workflow commands here sequentially + +# Lint + make lint +# License Checker + .github/check-license-headers.sh +# Unit Test + make test-unit race=true +# Benchmarks Test + make test-bench +# Integration Test +### OpenSearch + make cluster.clean cluster.build cluster.start + make test-integ race=true + make cluster.stop + +##@ Other +#------------------------------------------------------------------------------ +help: ## Display help + @awk 'BEGIN {FS = ":.*##"; printf "Usage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) +#------------- -------------- + +.DEFAULT_GOAL := help +.PHONY: help backport cluster cluster.clean coverage godoc lint release test test-bench test-integ test-unit linters linters.install +.SILENT: lint.markdown diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/NOTICE.txt b/vendor/github.com/opensearch-project/opensearch-go/v4/NOTICE.txt new file mode 100644 index 0000000000..eec263f0c9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/NOTICE.txt @@ -0,0 +1,8 @@ +OpenSearch (https://opensearch.org/) +Copyright 2021 OpenSearch Contributors + +This product includes software developed by +Elasticsearch (http://www.elastic.co). + +This product includes software developed by The Apache Software +Foundation (http://www.apache.org/). \ No newline at end of file diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/OpenSearch.svg b/vendor/github.com/opensearch-project/opensearch-go/v4/OpenSearch.svg new file mode 100644 index 0000000000..bd4ae0fe83 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/OpenSearch.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/README.md b/vendor/github.com/opensearch-project/opensearch-go/v4/README.md new file mode 100644 index 0000000000..5824b12625 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/README.md @@ -0,0 +1,42 @@ +[![Go Reference](https://pkg.go.dev/badge/github.com/opensearch-project/opensearch-go.svg)](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v4) [![Build](https://github.com/opensearch-project/opensearch-go/actions/workflows/lint.yml/badge.svg)](https://github.com/opensearch-project/opensearch-go/actions/workflows/lint.yml) [![Unit](https://github.com/opensearch-project/opensearch-go/actions/workflows/test-unit.yml/badge.svg)](https://github.com/opensearch-project/opensearch-go/actions/workflows/test-unit.yml) [![Integration](https://github.com/opensearch-project/opensearch-go/actions/workflows/test-integration.yml/badge.svg)](https://github.com/opensearch-project/opensearch-go/actions/workflows/test-integration.yml) [![codecov](https://codecov.io/gh/opensearch-project/opensearch-go/branch/main/graph/badge.svg?token=MI9g3KYHVx)](https://codecov.io/gh/opensearch-project/opensearch-go) [![Chat](https://img.shields.io/badge/chat-on%20forums-blue)](https://discuss.opendistrocommunity.dev/c/clients/) ![PRs welcome!](https://img.shields.io/badge/PRs-welcome!-success) + +![OpenSearch logo](OpenSearch.svg) + +OpenSearch Go Client + +- [Welcome!](#welcome) +- [Project Resources](#project-resources) +- [Code of Conduct](#code-of-conduct) +- [License](#license) +- [Copyright](#copyright) + +## Welcome! + +**opensearch-go** is [a community-driven, open source fork](https://aws.amazon.com/blogs/opensource/introducing-opensearch/) of go-elasticsearch licensed under the [Apache v2.0 License](LICENSE.txt). For more information, see [opensearch.org](https://opensearch.org/). + +## Project Resources + +- [Project Website](https://opensearch.org/) +- [Developer Guide](DEVELOPER_GUIDE.md) +- [User Guide](USER_GUIDE.md) +- [Documentation](https://opensearch.org/docs/latest/clients/go/) +- [API Documentation](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v4) +- Need help? Try [Forums](https://discuss.opendistrocommunity.dev/c/clients/) +- [Project Principles](https://opensearch.org/#principles) +- [Contributing to OpenSearch](CONTRIBUTING.md) +- [Maintainer Responsibilities](MAINTAINERS.md) +- [Release Management](RELEASING.md) +- [Admin Responsibilities](ADMINS.md) +- [Security](SECURITY.md) + +## Code of Conduct + +This project has adopted the [Amazon Open Source Code of Conduct](CODE_OF_CONDUCT.md). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq), or contact [opensource-codeofconduct@amazon.com](mailto:opensource-codeofconduct@amazon.com) with any additional questions or comments. + +## License + +This project is licensed under the [Apache v2.0 License](LICENSE.txt). + +## Copyright + +Copyright OpenSearch Contributors. See [NOTICE](NOTICE.txt) for details. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/RELEASING.md b/vendor/github.com/opensearch-project/opensearch-go/v4/RELEASING.md new file mode 100644 index 0000000000..f6ecb7b123 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/RELEASING.md @@ -0,0 +1,61 @@ +- [Overview](#overview) +- [Branching](#branching) + - [Release Branching](#release-branching) + - [Feature Branches](#feature-branches) +- [Release Labels](#release-labels) +- [Releasing](#releasing) + +## Overview + +This document explains the release strategy for artifacts in this organization. + +## Branching + +### Release Branching + +Given the current major release of 1.0, projects in this organization maintain the following active branches. + +- **main**: The next _major_ release. This is the branch where all merges take place and code moves fast. +- **1.x**: The next _minor_ release. Once a change is merged into `main`, decide whether to backport it to `1.x`. +- **1.0**: The _current_ release. In between minor releases, only hotfixes (e.g. security) are backported to `1.0`. + +Label PRs with the next major version label (e.g. `2.0.0`) and merge changes into `main`. Label PRs that you believe need to be backported as `1.x` and `1.0`. Backport PRs by checking out the versioned branch, cherry-pick changes and open a PR against each target backport branch. + +### Feature Branches + +Do not creating branches in the upstream repo, use your fork, for the exception of long lasting feature branches that require active collaboration from multiple developers. Name feature branches `feature/`. Once the work is merged to `main`, please make sure to delete the feature branch. + +## Release Labels + +Repositories create consistent release labels, such as `v1.0.0`, `v1.1.0` and `v2.0.0`, as well as `patch` and `backport`. Use release labels to target an issue or a PR for a given release. See [MAINTAINERS](MAINTAINERS.md#triage-open-issues) for more information on triaging issues. + +## Releasing + +The release process is standard across repositories in this org and is run by a release manager volunteering from amongst [MAINTAINERS](MAINTAINERS.md). + +1. Ensure that the version in [version.go](internal/version/version.go) is correct for the next release. The example here releases version 4.3.0. +2. For major version releases, ensure that all references are up-to-date, e.g. `github.com/opensearch-project/opensearch-go/v4`, see [opensearch-go#444](https://github.com/opensearch-project/opensearch-go/pull/444). +3. Edit the [CHANGELOG](CHANGELOG.md) and replace the `Unreleased` section with the version about to be released. +4. Add a comparison link to the new version at the bottom of the [CHANGELOG](CHANGELOG.md). +5. Create a pull request with the changes into `main`, e.g. [opensearch-go#443](https://github.com/opensearch-project/opensearch-go/pull/443). +6. Create a tag, e.g. `v4.3.0`, and push it to the GitHub repo. This [makes the new version available](https://go.dev/doc/modules/publishing) on [pkg.go.dev](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v4). +7. Draft and publish a [new GitHub release](https://github.com/opensearch-project/opensearch-go/releases/new) from the newly created tag. +8. Create a new `Unreleased` section in the [CHANGELOG](CHANGELOG.md), increment version in [version.go](internal/version/version.go) to the next developer iteration (e.g. `4.3.1`), and make a pull request with this change into `main`, e.g. [opensearch-go#448](https://github.com/opensearch-project/opensearch-go/pull/448). + ``` + ## [Unreleased] + + ### Added + + ### Changed + + ### Deprecated + + ### Removed + + ### Fixed + + ### Security + + ### Dependencies + ``` +9. Run `go list` with the new version to refresh [pkg.go.dev](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v4), e.g. `go list -m github.com/opensearch-project/opensearch-go/v4@v4.3.0`. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/SECURITY.md b/vendor/github.com/opensearch-project/opensearch-go/v4/SECURITY.md new file mode 100644 index 0000000000..b862921043 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/SECURITY.md @@ -0,0 +1,3 @@ +## Reporting a Vulnerability + +If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/) or directly via email to aws-security@amazon.com. Please do **not** create a public GitHub issue. diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/UPGRADING.md b/vendor/github.com/opensearch-project/opensearch-go/v4/UPGRADING.md new file mode 100644 index 0000000000..3e5473113f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/UPGRADING.md @@ -0,0 +1,307 @@ +- [Upgrading Opensearch GO Client](#upgrading-opensearch-go-client) + - [Upgrading to >= 4.0.0](#upgrading-to->=-4.0.0) + - [error types](#error-types) + - [Upgrading to >= 3.0.0](#upgrading-to->=-3.0.0) + - [client creation](#client-creation) + - [requests](#requests) + - [responses](#responses) + - [error handing](#error-handling) + - [Upgrading to >= 2.3.0](#upgrading-to->=-2.3.0) + - [snapshot delete](#snapshot-delete) + +# Upgrading Opensearch GO Client + +## Upgrading to >= 5.0.0 +Version 5.0.0 returns `*opensearch.StringError` error type instead of `*fmt.wrapError` when response received from the server is an unknown JSON. For example, consider delete document API which returns an unknown JSON body when document is not found. + +Before 5.0.0: +```go +docDelResp, err = client.Document.Delete(ctx, opensearchapi.DocumentDeleteReq{Index: "movies", DocumentID: "3"}) +if err != nil { + fmt.Println(err) + + if !errors.Is(err, opensearch.ErrJSONUnmarshalBody) && docDelResp != nil { + resp := docDelResp.Inspect().Response + // get http status + fmt.Println(resp.StatusCode) + body := strings.TrimPrefix(err.Error(), "opensearch error response could not be parsed as error: ") + errResp := opensearchapi.DocumentDeleteResp{} + json.Unmarshal([]byte(body), &errResp) + // extract result field from the body + fmt.Println(errResp.Result) + } +} +``` + +After 5.0.0: +```go +docDelResp, err = client.Document.Delete(ctx, opensearchapi.DocumentDeleteReq{Index: "movies", DocumentID: "3"}) +if err != nil { + // parse into *opensearch.StringError + var myStringErr *opensearch.StringError + if errors.As(err, &myStringErr) { + // get http status + fmt.Println(myStringErr.Status) + errResp := opensearchapi.DocumentDeleteResp{} + json.Unmarshal([]byte(myStringErr.Err), &errResp) + // extract result field from the body + fmt.Println(errResp.Result) + } +} +``` + + +## Upgrading to >= 4.0.0 + +Version 4.0.0 moved the error types, added with 3.0.0, from opensearchapi to opensearch, renamed them and added new error types. + +### Error Types + +Before 4.0.0: +Error types: +- `opensearchapi.Error` +- `opensearchapi.StringError` + +With 4.0.0: +Error types +- `opensearch.Error` +- `opensearch.StringError` +- `opensearch.ReasonError` +- `opensearch.MessageError` +- `opensearch.StructError` (which was the `opensearchapi.Error`) + +## Upgrading to >= 3.0.0 + +Version 3.0.0 is a major refactor of the client. + +### Client Creation +You now create the client from the opensearchapi and not from the opensearch lib. This was done to make the different APIs independent from each other. Plugin APIs like Security will get there own folder and therefore its own sub-lib. + +Before 3.0.0: +```go +// default client +client, err := opensearch.NewDefaultClient() + +// with config +client, err := opensearch.NewClient( + opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", + Password: "admin", + }, +) +``` + +With 3.0.0: + +```go +// default client +client, err := opensearchapi.NewDefaultClient() + +// with config +client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "admin", + }, + }, +) +``` + +### Requests + +Prior version 3.0.0 there were two options on how to perform requests. You could either use the request struct of the wished function and execute it with the client .Do() function or use the client function and add wanted args with so called With() functions. With the new version you now use functions attached to the client and give a context and the wanted request body as argument. + +Before 3.0.0: + +```go +// using the client function and adding args by using the With() functions +createIndex, err := client.Indices.Create( + "some-index", + client.Indices.Create.WithContext(ctx), + client.Indices.Create.WithBody(strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`)), +) + +// using the request struct +createIndex := opensearchapi.IndicesCreateRequest{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), +} +createIndexResponse, err := createIndex.Do(ctx, client) +``` + +With 3.0.0: + +```go +createIndexResponse, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) +``` + + +### Responses + +With the version 3.0.0 the lib no longer returns the opensearch.Response which is just a wrap up http.Response. Instead it will check the response for errors and try to parse the body into existing structs. Please note that some responses are so complex that we parse them as [json.RawMessage](https://pkg.go.dev/encoding/json#RawMessage) so you can parse them to your expected struct. If you need the opensearch.Response, then you can call .Inspect(). + +Before 3.0.0: + +```go +// Create the request +createIndex := opensearchapi.IndicesCreateRequest{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), +} +// Execute the requests +resp, err := createIndex.Do(ctx, client) +if err != nil { + return err +} +// Close the body +defer resp.Body.Close() + +// Check if the status code is >299 +if resp.IsError() { + return fmt.Errorf("Opensearch Returned an error: %#v", resp) +} + +// Create a struct that represents the create index response +createResp := struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` +} + +// Try to parse the response into the created struct +if err := json.NewDecoder(resp.Body).Decode(&createResp); err != nil { + return fmt.Errorf("Undexpected response body: %s, %#v, %s"resp.StatusCode, resp.Body, err) +} +// Print the created index name +fmt.Println(createResp.Index) +``` + +With 3.0.0: + +```go +// Create and execute the requests +createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) +if err != nil { + return err +} +// Print the created index name +fmt.Println(createResp.Index) + +// To get the opensearch.Response/http.Response +rawResp := createResp.Inspect().Response +``` + +### Error Handling + +With opensearch-go >= 3.0.0 opensearchapi responses are now checked for errors. Checking for errors twice is no longer needed. + +Prior versions only returned an error if the request failed to execute. For example if the client can't reach the server or the TLS handshake failed. With opensearch-go >= 3.0.0 each opensearchapi requests will return an error if the response http status code is > 299. The error can be parsed into the new `opensearchapi.Error` type by using `errors.As` to match for exceptions and get a more detailed view. + +Before 3.0.0: + +```go +// Create the request +createIndex := opensearchapi.IndicesCreateRequest{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), +} + +// Execute the requests +resp, err := createIndex.Do(ctx, client) +if err != nil { + return err +} +// Close the body +defer resp.Body.Close() + +// Check if the status code is >299 +if createIndexResp.IsError() { + fmt.Errorf("Opensearch returned an error. Status: %d", createIndexResp.StatusCode) +} +``` + +With 3.0.0: + +```go +var opensearchError opensearchapi.Error +// Create and execute the requests +createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) +// Load err into opensearchapi.Error to access the fields and tolerate if the index already exists +if err != nil { + if errors.As(err, &opensearchError) { + if opensearchError.Err.Type != "resource_already_exists_exception" { + return err + } + } else { + return err + } +} +``` + +## Upgrading to >= 2.3.0 + +### Snapshot Delete + +`SnapshotDeleteRequest` and `SnapshotDelete` changed the argument `Snapshot` type from `string` to `[]string`. + +Before 2.3.0: + +```go +// If you have a string containing your snapshot +stringSnapshotsToDelete := "snapshot-1,snapshot-2" +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: stringSnapshotsToDelete, +} + +// If you have a slice of strings containing your snapshot +sliceSnapshotToDelete := []string{"snapshot-1","snapshot-2"} +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: strings.Join(sliceSnapshotsToDelete, ","), +} +``` + +With 2.3.0: + +```go +// If you have a string containing your snapshots +stringSnapshotsToDelete := strings.Split("snapshot-1,snapshot-2", ",") +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: stringSnapshotsToDelete, +} + +// If you have a slice of strings containing your snapshots +sliceSnapshotToDelete := []string{"snapshot-1", "snapshot-2"} +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: sliceSnapshotsToDelete, +``` diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/USER_GUIDE.md b/vendor/github.com/opensearch-project/opensearch-go/v4/USER_GUIDE.md new file mode 100644 index 0000000000..edef4d3583 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/USER_GUIDE.md @@ -0,0 +1,399 @@ +- [User Guide](#user-guide) + - [Example](#example) + - [Amazon OpenSearch Service](#amazon-opensearch-service) + - [AWS SDK v1](#aws-sdk-v1) + - [AWS SDK v2](#aws-sdk-v2) + - [Guides by Topic](#guides-by-topic) + +# User Guide + +## Example + +In the example below, we create a client, an index with non-default settings, insert a document to the index, search for the document, delete the document and finally delete the index. + +```go +package main + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net/http" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" + "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + "github.com/opensearch-project/opensearch-go/v4/opensearchutil" +) + +const IndexName = "go-test-index1" + +func main() { + if err := example(); err != nil { + fmt.Printf("Error: %s\n", err) + os.Exit(1) + } +} + +func example() error { + // Initialize the client with SSL/TLS enabled. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "myStrongPassword123!", + }, + }, + ) + if err != nil { + return err + } + + ctx := context.Background() + // Print OpenSearch version information on console. + infoResp, err := client.Info(ctx, nil) + if err != nil { + return err + } + fmt.Printf("Cluster INFO:\n Cluster Name: %s\n Cluster UUID: %s\n Version Number: %s\n", infoResp.ClusterName, infoResp.ClusterUUID, infoResp.Version.Number) + + // Define index mapping. + // Note: these particular settings (eg, shards/replicas) + // will have no effect in AWS OpenSearch Serverless + mapping := strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 4 + } + } + }`) + + // Create an index with non-default settings. + createIndexResponse, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: IndexName, + Body: mapping, + }, + ) + + var opensearchError *opensearch.StructError + + // Load err into opensearch.Error to access the fields and tolerate if the index already exists + if err != nil { + if errors.As(err, &opensearchError) { + if opensearchError.Err.Type != "resource_already_exists_exception" { + return err + } + } else { + return err + } + } + fmt.Printf("Created Index: %s\n Shards Acknowledged: %t\n", createIndexResponse.Index, createIndexResponse.ShardsAcknowledged) + + // When using a structure, the conversion process to io.Reader can be omitted using utility functions. + document := struct { + Title string `json:"title"` + Director string `json:"director"` + Year string `json:"year"` + }{ + Title: "Moneyball", + Director: "Bennett Miller", + Year: "2011", + } + + docId := "1" + insertResp, err := client.Index( + ctx, + opensearchapi.IndexReq{ + Index: IndexName, + DocumentID: docId, + Body: opensearchutil.NewJSONReader(&document), + Params: opensearchapi.IndexParams{ + Refresh: "true", + }, + }, + ) + if err != nil { + return err + } + fmt.Printf("Created document in %s\n ID: %s\n", insertResp.Index, insertResp.ID) + + // Search for the document. + content := strings.NewReader(`{ + "size": 5, + "query": { + "multi_match": { + "query": "miller", + "fields": ["title^2", "director"] + } + } + }`) + + searchResp, err := client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: content, + }, + ) + if err != nil { + return err + } + fmt.Printf("Search hits: %v\n", searchResp.Hits.Total.Value) + + if searchResp.Hits.Total.Value > 0 { + indices := make([]string, 0) + for _, hit := range searchResp.Hits.Hits { + add := true + for _, index := range indices { + if index == hit.Index { + add = false + } + } + if add { + indices = append(indices, hit.Index) + } + } + fmt.Printf("Search indices: %s\n", strings.Join(indices, ",")) + } + + // Delete the document. + deleteReq := opensearchapi.DocumentDeleteReq{ + Index: IndexName, + DocumentID: docId, + } + + deleteResponse, err := client.Document.Delete(ctx, deleteReq) + if err != nil { + return err + } + fmt.Printf("Deleted document: %t\n", deleteResponse.Result == "deleted") + + // Delete previously created index. + deleteIndex := opensearchapi.IndicesDeleteReq{Indices: []string{IndexName}} + + deleteIndexResp, err := client.Indices.Delete(ctx, deleteIndex) + if err != nil { + return err + } + fmt.Printf("Deleted index: %t\n", deleteIndexResp.Acknowledged) + + // Try to delete the index again which fails as it does not exist + _, err = client.Indices.Delete(ctx, deleteIndex) + + // Load err into opensearchapi.Error to access the fields and tolerate if the index is missing + if err != nil { + if errors.As(err, &opensearchError) { + if opensearchError.Err.Type != "index_not_found_exception" { + return err + } + } else { + return err + } + } + return nil +} + +``` + +## Amazon OpenSearch Service + +Before starting, we strongly recommend reading the full AWS documentation regarding using IAM credentials to sign requests to OpenSearch APIs. See [Identity and Access Management in Amazon OpenSearch Service.](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/ac.html) + +> Even if you configure a completely open resource-based access policy, all requests to the OpenSearch Service configuration API must be signed. If your policies specify IAM users or roles, requests to the OpenSearch APIs also must be signed using AWS Signature Version 4. +> +> See [Managed Domains signing-service requests.](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/ac.html#managedomains-signing-service-requests) + +Depending on the version of AWS SDK used, import the v1 or v2 request signer from `signer/aws` or `signer/awsv2` respectively. Both signers are equivalent in their functionality, they provide AWS Signature Version 4 (SigV4). + +To read more about SigV4 see [Signature Version 4 signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) + +Here are some Go samples that show how to sign each OpenSearch request and automatically search for AWS credentials from the ~/.aws folder or environment variables: + +### AWS SDK v1 + +```go +package main + +import ( + "context" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws/session" + requestsigner "github.com/opensearch-project/opensearch-go/v4/signer/aws" + + "github.com/opensearch-project/opensearch-go/v4" + "github.com/opensearch-project/opensearch-go/v4/opensearchapi" +) + +const IndexName = "go-test-index1" + +func main() { + if err := example(); err != nil { + fmt.Printf("Error: %s\n", err) + os.Exit(1) + } +} + +const endpoint = "" // e.g. https://opensearch-domain.region.com + +func example() error { + // Create an AWS request Signer and load AWS configuration using default config folder or env vars. + // See https://docs.aws.amazon.com/opensearch-service/latest/developerguide/request-signing.html#request-signing-go + signer, err := requestsigner.NewSignerWithService( + session.Options{SharedConfigState: session.SharedConfigEnable}, + requestsigner.OpenSearchService, // Use requestsigner.OpenSearchServerless for Amazon OpenSearch Serverless. + ) + if err != nil { + return err + } + // Create an opensearch client and use the request-signer. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + }, + }, + ) + if err != nil { + return err + } + + ctx := context.Background() + + ping, err := client.Ping(ctx, nil) + if err != nil { + return err + } + + fmt.Println(ping) + + return nil +} +``` + +### AWS SDK v2 + +Use the AWS SDK v2 for Go to authenticate with Amazon OpenSearch service. + +```go +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + + "github.com/opensearch-project/opensearch-go/v4" + "github.com/opensearch-project/opensearch-go/v4/opensearchapi" + requestsigner "github.com/opensearch-project/opensearch-go/v4/signer/awsv2" +) + +const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} +func example() error { + ctx := context.Background() + + awsCfg, err := config.LoadDefaultConfig(ctx, + config.WithRegion(""), + config.WithCredentialsProvider( + getCredentialProvider("", "", ""), + ), + ) + if err != nil { + return err + } + + // Create an AWS request Signer and load AWS configuration using default config folder or env vars. + signer, err := requestsigner.NewSignerWithService(awsCfg, "es") // Use "aoss" for Amazon OpenSearch Serverless + if err != nil { + return err + } + + // Create an opensearch client and use the request-signer. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + }, + }, + ) + if err != nil { + return err + } + + indexName := "go-test-index" + + // Define index mapping. + mapping := strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 4 + } + } + }`) + + // Create an index with non-default settings. + createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: indexName, + Body: mapping, + }, + ) + if err != nil { + return err + } + + fmt.Printf("created index: %s\n", createResp.Index) + + delResp, err := client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Indices: []string{indexName}}) + if err != nil { + return err + } + + fmt.Printf("deleted index: %#v\n", delResp.Acknowledged) + return nil +} + +func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc { + return func(ctx context.Context) (aws.Credentials, error) { + c := &aws.Credentials{ + AccessKeyID: accessKey, + SecretAccessKey: secretAccessKey, + SessionToken: token, + } + return *c, nil + } +} +``` + +## Guides by Topic + +- [Index Lifecycle](guides/index_lifecycle.md) +- [Document Lifecycle](guides/document_lifecycle.md) +- [Search](guides/search.md) +- [Bulk](guides/bulk.md) +- [Advanced Index Actions](guides/advanced_index_actions.md) +- [Index Templates](guides/index_template.md) +- [Data Streams](guides/data_streams.md) +- [Retry and Backoff](guides/retry_backoff.md) diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/doc.go b/vendor/github.com/opensearch-project/opensearch-go/v4/doc.go new file mode 100644 index 0000000000..b2bfd6398c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/doc.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to opensearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +/* +Package opensearch provides a Go client for OpenSearch. + +Create the client with the NewDefaultClient function: + + opensearch.NewDefaultClient() + +The OPENSEARCH_URL/ELASTICSEARCH_URL environment variable is used instead of the default URL, when set. +Use a comma to separate multiple URLs. +It is an error to set both environment variable. + +To configure the client, pass a Config object to the NewClient function: + + cfg := opensearch.Config{ + Addresses: []string{ + "http://localhost:9200", + "http://localhost:9201", + }, + Username: "foo", + Password: "bar", + Transport: &http.Transport{ + MaxIdleConnsPerHost: 10, + ResponseHeaderTimeout: time.Second, + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS11, + }, + }, + } + + opensearch.NewClient(cfg) + +See the opensearch_integration_test.go file for more information. + +Call the OpenSearch APIs by invoking the corresponding methods on the client: + + res, err := client.Info() + if err != nil { + log.Fatalf("Error getting response: %s", err) + } + + log.Println(res) + +See the github.com/opensearch-project/opensearch-go/opensearchapi package for more information about using the API. + +See the github.com/opensearch-project/opensearch-go/opensearchtransport package for more information about configuring the transport. +*/ +package opensearch diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/error.go b/vendor/github.com/opensearch-project/opensearch-go/v4/error.go new file mode 100644 index 0000000000..92016c4036 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/error.go @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearch + +import ( + "encoding/json" + "errors" + "fmt" + "io" +) + +// Error vars +var ( + ErrUnexpectedEmptyBody = errors.New("body is unexpectedly empty") + ErrReadBody = errors.New("failed to read body") + ErrJSONUnmarshalBody = errors.New("failed to json unmarshal body") + ErrUnknownOpensearchError = errors.New("opensearch error response could not be parsed as error") +) + +// Error represents an Opensearch error with only an error field +type Error struct { + Err string `json:"error"` +} + +// Error returns a string +func (e Error) Error() string { + return fmt.Sprintf("error: %s", e.Err) +} + +// StringError represnets an Opensearch error where error is a string +type StringError struct { + Err string `json:"error"` + Status int `json:"status"` +} + +// Error returns a string +func (e StringError) Error() string { + return fmt.Sprintf("status: %d, error: %s", e.Status, e.Err) +} + +// ReasonError represents an Opensearch error with a reason field +type ReasonError struct { + Reason string `json:"reason"` + Status string `json:"status"` +} + +// Error returns a string +func (e ReasonError) Error() string { + return fmt.Sprintf("status: %s, reason: %s", e.Status, e.Reason) +} + +// MessageError represents an Opensearch error with a message field +type MessageError struct { + Message string `json:"message"` + Status string `json:"status"` +} + +// Error returns a string +func (e MessageError) Error() string { + return fmt.Sprintf("status: %s, message: %s", e.Status, e.Message) +} + +// StructError represents an Opensearch error with a detailed error struct +type StructError struct { + Err Err `json:"error"` + Status int `json:"status"` +} + +// Err represents the error of an API error response +type Err struct { + RootCause []RootCause `json:"root_cause"` + Type string `json:"type"` + Reason string `json:"reason"` + Index string `json:"index,omitempty"` + IndexUUID string `json:"index_uuid,omitempty"` +} + +// RootCause represents the root_cause of an API error response +type RootCause struct { + Type string `json:"type"` + Reason string `json:"reason"` + Index string `json:"index,omitempty"` + IndexUUID string `json:"index_uuid,omitempty"` +} + +// Error returns a string +func (e StructError) Error() string { + return fmt.Sprintf("status: %d, type: %s, reason: %s, root_cause: %s", e.Status, e.Err.Type, e.Err.Reason, e.Err.RootCause) +} + +// UnmarshalJSON is a custom unmarshal function for StructError returning custom errors in special cases +func (e *StructError) UnmarshalJSON(b []byte) error { + var dummy struct { + Err json.RawMessage `json:"error"` + Status int `json:"status"` + } + if err := json.Unmarshal(b, &dummy); err != nil { + return err + } + + var osErr Err + if err := json.Unmarshal(dummy.Err, &osErr); err != nil { + return &StringError{Status: dummy.Status, Err: string(dummy.Err)} + } + if dummy.Status == 0 || (osErr.Type == "" && osErr.Reason == "") { + return fmt.Errorf("%w: %s", ErrUnknownOpensearchError, b) + } + + e.Err = osErr + e.Status = dummy.Status + + return nil +} + +// ParseError tries to parse the opensearch error into an custom error +func ParseError(resp *Response) error { + if resp.Body == nil { + return fmt.Errorf("%w, status: %s", ErrUnexpectedEmptyBody, resp.Status()) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("%w: %w", ErrReadBody, err) + } + + var testResp struct { + Status any `json:"status"` + Error any `json:"error"` + Message any `json:"message"` + Reason any `json:"reason"` + } + if err = json.Unmarshal(body, &testResp); err != nil { + return fmt.Errorf("%w: %w", ErrJSONUnmarshalBody, err) + } + + // Check for errors where status is a number + if _, ok := testResp.Status.(float64); ok { + // Check for errors where error is a string + if _, ok := testResp.Error.(string); ok { + var apiError StringError + return parseError(body, &apiError) + } + // Check for errors where error is a struct + if _, ok := testResp.Error.(map[string]any); ok { + var apiError StructError + return parseError(body, &apiError) + } + } + + // Check for errors where status is a string + if _, ok := testResp.Status.(string); ok { + // Check for erros where message is a string + if _, ok := testResp.Message.(string); ok { + var apiError MessageError + return parseError(body, &apiError) + } + // Check for errors where reason is a string + if _, ok := testResp.Reason.(string); ok { + var apiError ReasonError + return parseError(body, &apiError) + } + } + + // Check for errors that only contain the error field + if testResp.Status == nil && testResp.Message == nil && testResp.Reason == nil && testResp.Error != nil { + var apiError Error + return parseError(body, &apiError) + } + + return &StringError{Status: resp.StatusCode, Err: string(body)} +} + +func parseError(body []byte, errStruct error) error { + if err := json.Unmarshal(body, &errStruct); err != nil { + return fmt.Errorf("%w: %w: %s", ErrJSONUnmarshalBody, err, string(body)) + } + return errStruct +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/internal/version/version.go b/vendor/github.com/opensearch-project/opensearch-go/v4/internal/version/version.go new file mode 100644 index 0000000000..727cd12237 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/internal/version/version.go @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package version + +// Client returns the client version as a string. +const Client = "4.5.0" diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearch.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearch.go new file mode 100644 index 0000000000..b04e7c74e3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearch.go @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearch + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "regexp" + "strconv" + "strings" + "time" + + "github.com/opensearch-project/opensearch-go/v4/internal/version" + "github.com/opensearch-project/opensearch-go/v4/opensearchtransport" + "github.com/opensearch-project/opensearch-go/v4/signer" +) + +const ( + defaultURL = "http://localhost:9200" + openSearch = "opensearch" + unsupportedProduct = "the client noticed that the server is not a supported distribution" + envOpenSearchURL = "OPENSEARCH_URL" +) + +// Version returns the package version as a string. +const Version = version.Client + +// Error vars +var ( + ErrCreateClient = errors.New("cannot create client") + ErrCreateTransport = errors.New("error creating transport") + ErrParseVersion = errors.New("failed to parse opensearch version") + ErrParseURL = errors.New("cannot parse url") + ErrTransportMissingMethodMetrics = errors.New("transport is missing method Metrics()") + ErrTransportMissingMethodDiscoverNodes = errors.New("transport is missing method DiscoverNodes()") +) + +// Config represents the client configuration. +type Config struct { + Addresses []string // A list of nodes to use. + Username string // Username for HTTP Basic Authentication. + Password string // Password for HTTP Basic Authentication. + + Header http.Header // Global HTTP request header. + + Signer signer.Signer + + // PEM-encoded certificate authorities. + // When set, an empty certificate pool will be created, and the certificates will be appended to it. + // The option is only valid when the transport is not specified, or when it's http.Transport. + CACert []byte + + RetryOnStatus []int // List of status codes for retry. Default: 502, 503, 504. + DisableRetry bool // Default: false. + EnableRetryOnTimeout bool // Default: false. + MaxRetries int // Default: 3. + + CompressRequestBody bool // Default: false. + + DiscoverNodesOnStart bool // Discover nodes when initializing the client. Default: false. + DiscoverNodesInterval time.Duration // Discover nodes periodically. Default: disabled. + + EnableMetrics bool // Enable the metrics collection. + EnableDebugLogger bool // Enable the debug logging. + + RetryBackoff func(attempt int) time.Duration // Optional backoff duration. Default: nil. + + Transport http.RoundTripper // The HTTP transport object. + Logger opensearchtransport.Logger // The logger object. + Selector opensearchtransport.Selector // The selector object. + + // Optional constructor function for a custom ConnectionPool. Default: nil. + ConnectionPoolFunc func([]*opensearchtransport.Connection, opensearchtransport.Selector) opensearchtransport.ConnectionPool +} + +// Client represents the OpenSearch client. +type Client struct { + Transport opensearchtransport.Interface +} + +// NewDefaultClient creates a new client with default options. +// +// It will use http://localhost:9200 as the default address. +// +// It will use the OPENSEARCH_URL/ELASTICSEARCH_URL environment variable, if set, +// to configure the addresses; use a comma to separate multiple URLs. +// +// It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL. +func NewDefaultClient() (*Client, error) { + return NewClient(Config{}) +} + +// NewClient creates a new client with configuration from cfg. +// +// It will use http://localhost:9200 as the default address. +// +// It will use the OPENSEARCH_URL/ELASTICSEARCH_URL environment variable, if set, +// to configure the addresses; use a comma to separate multiple URLs. +// +// It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL. +func NewClient(cfg Config) (*Client, error) { + var addrs []string + + if len(cfg.Addresses) == 0 { + envAddress := getAddressFromEnvironment() + addrs = envAddress + } else { + addrs = append(addrs, cfg.Addresses...) + } + + urls, err := addrsToURLs(addrs) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrCreateClient, err) + } + + if len(urls) == 0 { + //nolint:errcheck // errcheck exclude ??? + u, _ := url.Parse(defaultURL) + urls = append(urls, u) + } + + // TODO: Refactor + if urls[0].User != nil { + cfg.Username = urls[0].User.Username() + pw, _ := urls[0].User.Password() + cfg.Password = pw + } + + tp, err := opensearchtransport.New(opensearchtransport.Config{ + URLs: urls, + Username: cfg.Username, + Password: cfg.Password, + + Header: cfg.Header, + CACert: cfg.CACert, + + Signer: cfg.Signer, + + RetryOnStatus: cfg.RetryOnStatus, + DisableRetry: cfg.DisableRetry, + EnableRetryOnTimeout: cfg.EnableRetryOnTimeout, + MaxRetries: cfg.MaxRetries, + RetryBackoff: cfg.RetryBackoff, + + CompressRequestBody: cfg.CompressRequestBody, + + EnableMetrics: cfg.EnableMetrics, + EnableDebugLogger: cfg.EnableDebugLogger, + + DiscoverNodesInterval: cfg.DiscoverNodesInterval, + + Transport: cfg.Transport, + Logger: cfg.Logger, + Selector: cfg.Selector, + ConnectionPoolFunc: cfg.ConnectionPoolFunc, + }) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrCreateTransport, err) + } + + client := &Client{Transport: tp} + + if cfg.DiscoverNodesOnStart { + //nolint:errcheck // goroutine discards return values + go client.DiscoverNodes() + } + + return client, err +} + +func getAddressFromEnvironment() []string { + return addrsFromEnvironment(envOpenSearchURL) +} + +// ParseVersion returns an int64 representation of version. +func ParseVersion(version string) (int64, int64, int64, error) { + reVersion := regexp.MustCompile(`^([0-9]+)\.([0-9]+)\.([0-9]+)`) + matches := reVersion.FindStringSubmatch(version) + //nolint:gomnd // 4 is the minium regexp match length + if len(matches) < 4 { + return 0, 0, 0, fmt.Errorf("%w: regexp does not match on version string", ErrParseVersion) + } + + major, err := strconv.ParseInt(matches[1], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) + } + + minor, err := strconv.ParseInt(matches[2], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) + } + + patch, err := strconv.ParseInt(matches[3], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) + } + + return major, minor, patch, nil +} + +// Perform delegates to Transport to execute a request and return a response. +func (c *Client) Perform(req *http.Request) (*http.Response, error) { + // Perform the original request. + return c.Transport.Perform(req) +} + +// Do gets and performs the request. It also tries to parse the response into the dataPointer +func (c *Client) Do(ctx context.Context, req Request, dataPointer interface{}) (*Response, error) { + httpReq, err := req.GetRequest() + if err != nil { + return nil, err + } + + if ctx != nil { + httpReq = httpReq.WithContext(ctx) + } + + //nolint:bodyclose // body got already closed by Perform, this is a nopcloser + resp, err := c.Perform(httpReq) + if err != nil { + return nil, err + } + + response := &Response{ + StatusCode: resp.StatusCode, + Body: resp.Body, + Header: resp.Header, + } + + if dataPointer != nil && resp.Body != nil && !response.IsError() { + data, err := io.ReadAll(resp.Body) + if err != nil { + return response, fmt.Errorf("%w, status: %d, err: %w", ErrReadBody, resp.StatusCode, err) + } + + response.Body = io.NopCloser(bytes.NewReader(data)) + + if err := json.Unmarshal(data, dataPointer); err != nil { + return response, fmt.Errorf("%w, status: %d, body: %s, err: %w", ErrJSONUnmarshalBody, resp.StatusCode, data, err) + } + } + + return response, nil +} + +// Metrics returns the client metrics. +func (c *Client) Metrics() (opensearchtransport.Metrics, error) { + if mt, ok := c.Transport.(opensearchtransport.Measurable); ok { + return mt.Metrics() + } + + return opensearchtransport.Metrics{}, ErrTransportMissingMethodMetrics +} + +// DiscoverNodes reloads the client connections by fetching information from the cluster. +func (c *Client) DiscoverNodes() error { + if dt, ok := c.Transport.(opensearchtransport.Discoverable); ok { + return dt.DiscoverNodes() + } + + return ErrTransportMissingMethodDiscoverNodes +} + +// addrsFromEnvironment returns a list of addresses by splitting +// the given environment variable with comma, or an empty list. +func addrsFromEnvironment(name string) []string { + var addrs []string + + if envURLs, ok := os.LookupEnv(name); ok && envURLs != "" { + list := strings.Split(envURLs, ",") + addrs = make([]string, len(list)) + + for idx, u := range list { + addrs[idx] = strings.TrimSpace(u) + } + } + + return addrs +} + +// addrsToURLs creates a list of url.URL structures from url list. +func addrsToURLs(addrs []string) ([]*url.URL, error) { + urls := make([]*url.URL, 0) + + for _, addr := range addrs { + u, err := url.Parse(strings.TrimRight(addr, "/")) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrParseURL, err) + } + + urls = append(urls, u) + } + + return urls, nil +} + +// ToPointer converts any value to a pointer, mainly used for request parameters +func ToPointer[V any](value V) *V { + return &value +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases-params.go new file mode 100644 index 0000000000..8705d7e680 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// AliasesParams represents possible parameters for the AliasesReq +type AliasesParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r AliasesParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases.go new file mode 100644 index 0000000000..5967894b6b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_aliases.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Aliases executes an /_aliases request with the required AliasesReq +func (c Client) Aliases(ctx context.Context, req AliasesReq) (*AliasesResp, error) { + var ( + data AliasesResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// AliasesReq represents possible options for the / request +type AliasesReq struct { + Body io.Reader + + Header http.Header + Params AliasesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_aliases", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// AliasesResp represents the returned struct of the / response +type AliasesResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasesResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk-params.go new file mode 100644 index 0000000000..c5af7d84a3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk-params.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// BulkParams represents possible parameters for the BulkReq +type BulkParams struct { + Pipeline string + Refresh string + RequireAlias *bool + Routing string + Source any + SourceExcludes []string + SourceIncludes []string + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r BulkParams) get() map[string]string { + params := make(map[string]string) + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk.go new file mode 100644 index 0000000000..854c07fd93 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_bulk.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Bulk executes a /_bulk request with the needed BulkReq +func (c Client) Bulk(ctx context.Context, req BulkReq) (*BulkResp, error) { + var ( + data BulkResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// BulkReq represents possible options for the /_bulk request +type BulkReq struct { + Index string + Body io.Reader + Header http.Header + Params BulkParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r BulkReq) GetRequest() (*http.Request, error) { + var path strings.Builder + //nolint:gomnd // 7 is the max number of static chars + path.Grow(7 + len(r.Index)) + + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + + path.WriteString("/_bulk") + + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// BulkResp represents the returned struct of the /_bulk response +type BulkResp struct { + Took int `json:"took"` + Errors bool `json:"errors"` + Items []map[string]BulkRespItem `json:"items"` + response *opensearch.Response +} + +// BulkRespItem represents an item of the BulkResp +type BulkRespItem struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Type string `json:"_type"` // Deprecated field + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Status int `json:"status"` + Error *struct { + Type string `json:"type"` + Reason string `json:"reason"` + Cause struct { + Type string `json:"type"` + Reason string `json:"reason"` + ScriptStack *[]string `json:"script_stack,omitempty"` + Script *string `json:"script,omitempty"` + Lang *string `json:"lang,omitempty"` + Position *struct { + Offset int `json:"offset"` + Start int `json:"start"` + End int `json:"end"` + } `json:"position,omitempty"` + Cause *struct { + Type string `json:"type"` + Reason *string `json:"reason"` + } `json:"caused_by"` + } `json:"caused_by,omitempty"` + } `json:"error,omitempty"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r BulkResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases-params.go new file mode 100644 index 0000000000..ddb9658803 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases-params.go @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatAliasesParams represents possible parameters for the CatAliasesReq +type CatAliasesParams struct { + ExpandWildcards string + H []string + Local *bool + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatAliasesParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases.go new file mode 100644 index 0000000000..a4485a68ce --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-aliases.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatAliasesReq represent possible options for the /_cat/aliases request +type CatAliasesReq struct { + Aliases []string + Header http.Header + Params CatAliasesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatAliasesReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Aliases, ",") + var path strings.Builder + path.Grow(len("/_cat/aliases/") + len(aliases)) + path.WriteString("/_cat/aliases") + if len(r.Aliases) > 0 { + path.WriteString("/") + path.WriteString(aliases) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatAliasesResp represents the returned struct of the /_cat/aliases response +type CatAliasesResp struct { + Aliases []CatAliasResp + response *opensearch.Response +} + +// CatAliasResp represents one index of the CatAliasesResp +type CatAliasResp struct { + Alias string `json:"alias"` + Index string `json:"index"` + Filter string `json:"filter"` + RoutingIndex string `json:"routing.index"` + RoutingSearch string `json:"routing.search"` + IsWriteIndex string `json:"is_write_index"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatAliasesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation-params.go new file mode 100644 index 0000000000..b3e0d09e01 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation-params.go @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatAllocationParams represents possible parameters for the CatAllocationReq +type CatAllocationParams struct { + Bytes string + ExpandWildcards string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatAllocationParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation.go new file mode 100644 index 0000000000..899533fe66 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-allocation.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatAllocationReq represent possible options for the /_cat/allocation request +type CatAllocationReq struct { + NodeIDs []string + Header http.Header + Params CatAllocationParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatAllocationReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeIDs, ",") + var path strings.Builder + path.Grow(len("/_cat/allocation/") + len(nodes)) + path.WriteString("/_cat/allocation") + if len(r.NodeIDs) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatAllocationsResp represents the returned struct of the /_cat/allocation response +type CatAllocationsResp struct { + Allocations []CatAllocationResp + response *opensearch.Response +} + +// CatAllocationResp represents one index of the CatAllocationResp +type CatAllocationResp struct { + Shards int `json:"shards,string"` + // Pointer of string as the api can returns null for those fileds with Node set to "UNASSIGNED" + DiskIndices *string `json:"disk.indices"` + DiskUsed *string `json:"disk.used"` + DiskAvail *string `json:"disk.avail"` + DiskTotal *string `json:"disk.total"` + DiskPercent *int `json:"disk.percent,string"` + Host *string `json:"host"` + IP *string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatAllocationsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager-params.go new file mode 100644 index 0000000000..9f84c9d2bc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatClusterManagerParams represents possible parameters for the CatClusterManagerReq +type CatClusterManagerParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatClusterManagerParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager.go new file mode 100644 index 0000000000..bf03671c29 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-cluster_manager.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatClusterManagerReq represent possible options for the /_cat/cluster_manager request +type CatClusterManagerReq struct { + Header http.Header + Params CatClusterManagerParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatClusterManagerReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/cluster_manager", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatClusterManagersResp represents the returned struct of the /_cat/cluster_manager response +type CatClusterManagersResp struct { + ClusterManagers []CatClusterManagerResp + response *opensearch.Response +} + +// CatClusterManagerResp represents one index of the CatClusterManagerResp +type CatClusterManagerResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatClusterManagersResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count-params.go new file mode 100644 index 0000000000..97223bdc67 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count-params.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatCountParams represents possible parameters for the CatCountReq +type CatCountParams struct { + H []string + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatCountParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count.go new file mode 100644 index 0000000000..0834245817 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-count.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatCountReq represent possible options for the /_cat/count request +type CatCountReq struct { + Indices []string + Header http.Header + Params CatCountParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatCountReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/count/") + len(indices)) + path.WriteString("/_cat/count") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatCountsResp represents the returned struct of the /_cat/count response +type CatCountsResp struct { + Counts []CatCountResp + response *opensearch.Response +} + +// CatCountResp represents one index of the CatCountResp +type CatCountResp struct { + Epoch int `json:"epoch,string"` + Timestamp string `json:"timestamp"` + Count int `json:"count,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatCountsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata-params.go new file mode 100644 index 0000000000..9a7fdde91b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata-params.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatFieldDataParams represents possible parameters for the CatFieldDataReq +type CatFieldDataParams struct { + Bytes string + H []string + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatFieldDataParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata.go new file mode 100644 index 0000000000..7ddefd1794 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-fielddata.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatFieldDataReq represent possible options for the /_cat/fielddata request +type CatFieldDataReq struct { + FieldData []string + Header http.Header + Params CatFieldDataParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatFieldDataReq) GetRequest() (*http.Request, error) { + fielddata := strings.Join(r.FieldData, ",") + var path strings.Builder + path.Grow(len("/_cat/fielddata/") + len(fielddata)) + path.WriteString("/_cat/fielddata") + if len(r.FieldData) > 0 { + path.WriteString("/") + path.WriteString(fielddata) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatFieldDataResp represents the returned struct of the /_cat/fielddata response +type CatFieldDataResp struct { + FieldData []CatFieldDataItemResp + response *opensearch.Response +} + +// CatFieldDataItemResp represents one index of the CatFieldDataResp +type CatFieldDataItemResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` + Field string `json:"field"` + Size string `json:"size"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatFieldDataResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health-params.go new file mode 100644 index 0000000000..b30a9dc985 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health-params.go @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatHealthParams represents possible parameters for the CatHealthReq +type CatHealthParams struct { + H []string + Sort []string + Time string + TS *bool + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatHealthParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.TS != nil { + params["ts"] = strconv.FormatBool(*r.TS) + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health.go new file mode 100644 index 0000000000..2ffe0f3180 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-health.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatHealthReq represent possible options for the /_cat/health request +type CatHealthReq struct { + Header http.Header + Params CatHealthParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatHealthReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/health", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatHealthResp represents the returned struct of the /_cat/health response +type CatHealthResp struct { + Health []CatHealthItemResp + response *opensearch.Response +} + +// CatHealthItemResp represents one index of the CatHealthResp +type CatHealthItemResp struct { + Epoch int `json:"epoch,string"` + Timestamp string `json:"timestamp"` + Cluster string `json:"cluster"` + Status string `json:"status"` + NodeTotal int `json:"node.total,string"` + NodeData int `json:"node.data,string"` + DiscoveredMaster bool `json:"discovered_master,string"` + DiscoveredClusterManager bool `json:"discovered_cluster_manager,string"` + Shards int `json:"shards,string"` + Primary int `json:"pri,string"` + Relocating int `json:"relo,string"` + Initializing int `json:"init,string"` + Unassigned int `json:"unassign,string"` + PendingTasks int `json:"pending_tasks,string"` + MaxTaskWaitTime string `json:"max_task_wait_time"` + ActiveShardsPercent string `json:"active_shards_percent"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatHealthResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices-params.go new file mode 100644 index 0000000000..ddbaab3e77 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices-params.go @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatIndicesParams represents possible parameters for the CatIndicesReq +type CatIndicesParams struct { + Bytes string + ExpandWildcards string + H []string + Health string + IncludeUnloadedSegments *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Primary *bool + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatIndicesParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Health != "" { + params["health"] = r.Health + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Primary != nil { + params["pri"] = strconv.FormatBool(*r.Primary) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices.go new file mode 100644 index 0000000000..28ddc18ea6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-indices.go @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatIndicesReq represent possible options for the /_cat/indices request +type CatIndicesReq struct { + Indices []string + Header http.Header + Params CatIndicesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatIndicesReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/indices/") + len(indices)) + path.WriteString("/_cat/indices") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatIndicesResp represents the returned struct of the /_cat/indices response +type CatIndicesResp struct { + Indices []CatIndexResp + response *opensearch.Response +} + +// CatIndexResp represents one index of the CatIndicesResp +type CatIndexResp struct { + Health string `json:"health"` + Status string `json:"status"` + Index string `json:"index"` + UUID string `json:"uuid"` + Primary *int `json:"pri,string"` + Replica *int `json:"rep,string"` + DocsCount *int `json:"docs.count,string"` + DocDeleted *int `json:"docs.deleted,string"` + CreationDate int `json:"creation.date,string"` + CreationDateString string `json:"creation.date.string"` + // Pointer as newly created indices can return null + StoreSize *string `json:"store.size"` + PrimaryStoreSize *string `json:"pri.store.size"` + CompletionSize *string `json:"completion.size"` + PrimaryCompletionSize *string `json:"pri.completion.size"` + FieldDataMemorySize *string `json:"fielddata.memory_size"` + PrimaryFieldDataMemorySize *string `json:"pri.fielddata.memory_size"` + FieldDataEvictions *int `json:"fielddata.evictions,string"` + PrimaryFieldDataEvictions *int `json:"pri.fielddata.evictions,string"` + QueryCacheMemorySize *string `json:"query_cache.memory_size"` + PrimaryQueryCacheMemorySize *string `json:"pri.query_cache.memory_size"` + QueryCacheEvictions *int `json:"query_cache.evictions,string"` + PrimaryQueryCacheEvictions *int `json:"pri.query_cache.evictions,string"` + RequestCacheMemorySize *string `json:"request_cache.memory_size"` + PrimaryRequestCacheMemorySize *string `json:"pri.request_cache.memory_size"` + RequestCacheEvictions *int `json:"request_cache.evictions,string"` + PrimaryRequestCacheEvictions *int `json:"pri.request_cache.evictions,string"` + RequestCacheHitCount *int `json:"request_cache.hit_count,string"` + PrimaryRequestCacheHitCount *int `json:"pri.request_cache.hit_count,string"` + RequestCacheMissCount *int `json:"request_cache.miss_count,string"` + PrimaryRequestCacheMissCount *int `json:"pri.request_cache.miss_count,string"` + FlushTotal *int `json:"flush.total,string"` + PrimaryFlushTotal *int `json:"pri.flush.total,string"` + FlushTime *string `json:"flush.total_time"` + PrimaryFlushTime *string `json:"pri.flush.total_time"` + GetCurrent *int `json:"get.current,string"` + PrimaryGetCurrent *int `json:"pri.get.current,string"` + GetTime *string `json:"get.time"` + PrimaryGetTime *string `json:"pri.get.time"` + GetTotal *int `json:"get.total,string"` + PrimaryGetTotal *int `json:"pri.get.total,string"` + GetExistsTime *string `json:"get.exists_time"` + PrimaryGetExistsTime *string `json:"pri.get.exists_time"` + GetExistsTotal *int `json:"get.exists_total,string"` + PrimaryGetExistsTotal *int `json:"pri.get.exists_total,string"` + GetMissingTime *string `json:"get.missing_time"` + PrimaryGetMissingTime *string `json:"pri.get.missing_time"` + GetMissingTotal *int `json:"get.missing_total,string"` + PrimaryGetMissingTotal *int `json:"pri.get.missing_total,string"` + IndexingDeleteCurrent *int `json:"indexing.delete_current,string"` + PrimaryIndexingDeleteCurrent *int `json:"pri.indexing.delete_current,string"` + IndexingDeleteTime *string `json:"indexing.delete_time"` + PrimaryIndexingDeleteTime *string `json:"pri.indexing.delete_time"` + IndexingDeleteTotal *int `json:"indexing.delete_total,string"` + PrimaryIndexingDeleteTotal *int `json:"pri.indexing.delete_total,string"` + IndexingIndexCurrent *int `json:"indexing.index_current,string"` + PrimaryIndexingIndexCurrent *int `json:"pri.indexing.index_current,string"` + IndexingIndexTime *string `json:"indexing.index_time"` + PrimaryIndexingIndexTime *string `json:"pri.indexing.index_time"` + IndexingIndexTotal *int `json:"indexing.index_total,string"` + PrimaryIndexingIndexTotal *int `json:"pri.indexing.index_total,string"` + IndexingIndexFailed *int `json:"indexing.index_failed,string"` + PrimaryIndexingIndexFailed *int `json:"pri.indexing.index_failed,string"` + MergesCurrent *int `json:"merges.current,string"` + PrimaryMergesCurrent *int `json:"pri.merges.current,string"` + MergesCurrentDocs *int `json:"merges.current_docs,string"` + PrimaryMergesCurrentDocs *int `json:"pri.merges.current_docs,string"` + MergesCurrentSize *string `json:"merges.current_size"` + PrimaryMergesCurrentSize *string `json:"pri.merges.current_size"` + MergesTotal *int `json:"merges.total,string"` + PrimaryMergesTotal *int `json:"pri.merges.total,string"` + MergesTotalDocs *int `json:"merges.total_docs,string"` + PrimaryMergesTotalDocs *int `json:"pri.merges.total_docs,string"` + MergesTotalSize *string `json:"merges.total_size"` + PrimaryMergesTotalSize *string `json:"pri.merges.total_size"` + MergesTotalTime *string `json:"merges.total_time"` + PrimaryMergesTotalTime *string `json:"pri.merges.total_time"` + RefreshTotal *int `json:"refresh.total,string"` + PrimaryRefreshTotal *int `json:"pri.refresh.total,string"` + RefreshTime *string `json:"refresh.time"` + PrimaryRefreshTime *string `json:"pri.refresh.time"` + RefreshExternalTotal *int `json:"refresh.external_total,string"` + PrimaryRefreshExternalTotal *int `json:"pri.refresh.external_total,string"` + RefreshExternalTime *string `json:"refresh.external_time"` + PrimaryRefreshExternalTime *string `json:"pri.refresh.external_time"` + RefreshListeners *int `json:"refresh.listeners,string"` + PrimaryRefreshListeners *int `json:"pri.refresh.listeners,string"` + SearchFetchCurrent *int `json:"search.fetch_current,string"` + PrimarySearchFetchCurrent *int `json:"pri.search.fetch_current,string"` + SearchFetchTime *string `json:"search.fetch_time"` + PrimarySearchFetchTime *string `json:"pri.search.fetch_time"` + SearchFetchTotal *int `json:"search.fetch_total,string"` + PrimarySearchFetchTotal *int `json:"pri.search.fetch_total,string"` + SearchOpenContexts *int `json:"search.open_contexts,string"` + PrimarySearchOpenContexts *int `json:"pri.search.open_contexts,string"` + SearchQueryCurrent *int `json:"search.query_current,string"` + PrimarySearchQueryCurrent *int `json:"pri.search.query_current,string"` + SearchQueryTime *string `json:"search.query_time"` + PrimarySearchQueryTime *string `json:"pri.search.query_time"` + SearchQueryTotal *int `json:"search.query_total,string"` + PrimarySearchQueryTotal *int `json:"pri.search.query_total,string"` + SearchConcurrentQueryCurrent *int `json:"search.concurrent_query_current,string"` + PrimarySearchConcurrentQueryCurrent *int `json:"pri.search.concurrent_query_current,string"` + SearchConcurrentQueryTime *string `json:"search.concurrent_query_time"` + PrimarySearchConcurrentQueryTime *string `json:"pri.search.concurrent_query_time"` + SearchConcurrentQueryTotal *int `json:"search.concurrent_query_total,string"` + PrimarySearchConcurrentQueryTotal *int `json:"pri.search.concurrent_query_total,string"` + SearchConcurrentAvgSliceCount *string `json:"search.concurrent_avg_slice_count"` + PrimarySearchConcurrentAvgSliceCount *string `json:"pri.search.concurrent_avg_slice_count"` + SearchScrollCurrent *int `json:"search.scroll_current,string"` + PrimarySearchScrollCurrent *int `json:"pri.search.scroll_current,string"` + SearchScrollTime *string `json:"search.scroll_time"` + PrimarySearchScrollTime *string `json:"pri.search.scroll_time"` + SearchScrollTotal *int `json:"search.scroll_total,string"` + PrimarySearchScrollTotal *int `json:"pri.search.scroll_total,string"` + SearchPointInTimeCurrent *string `json:"search.point_in_time_current"` + PrimarySearchPointInTimeCurrent *string `json:"pri.search.point_in_time_current"` + SearchPointInTimeTime *string `json:"search.point_in_time_time"` + PrimarySearchPointInTimeTime *string `json:"pri.search.point_in_time_time"` + SearchPointInTimeTotal *int `json:"search.point_in_time_total,string"` + PrimarySearchPointInTimeTotal *int `json:"pri.search.point_in_time_total,string"` + SegmentsCount *int `json:"segments.count,string"` + PrimarySegmentsCount *int `json:"pri.segments.count,string"` + SegmentsMemory *string `json:"segments.memory"` + PrimarySegmentsMemory *string `json:"pri.segments.memory"` + SegmentsIndexWriteMemory *string `json:"segments.index_writer_memory"` + PrimarySegmentsIndexWriteMemory *string `json:"pri.segments.index_writer_memory"` + SegmentsVersionMapMemory *string `json:"segments.version_map_memory"` + PrimarySegmentsVersionMapMemory *string `json:"pri.segments.version_map_memory"` + SegmentsFixedBitsetMemory *string `json:"segments.fixed_bitset_memory"` + PrimarySegmentsFixedBitsetMemory *string `json:"pri.segments.fixed_bitset_memory"` + WarmerCurrent *int `json:"warmer.current,string"` + PrimaryWarmerCurrent *int `json:"pri.warmer.current,string"` + WarmerTotal *int `json:"warmer.total,string"` + PrimaryWarmerTotal *int `json:"pri.warmer.total,string"` + WarmerTotalTime *string `json:"warmer.total_time"` + PrimaryWarmerTotalTime *string `json:"pri.warmer.total_time"` + SuggestCurrent *int `json:"suggest.current,string"` + PrimarySuggestCurrent *int `json:"pri.suggest.current,string"` + SuggestTime *string `json:"suggest.time"` + PrimarySuggestTime *string `json:"pri.suggest.time"` + SuggestTotal *int `json:"suggest.total,string"` + PrimarySuggestTotal *int `json:"pri.suggest.total,string"` + MemoryTotal string `json:"memory.total"` + PrimaryMemoryTotal string `json:"pri.memory.total"` + SearchThrottled bool `json:"search.throttled,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatIndicesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master-params.go new file mode 100644 index 0000000000..cbfec36858 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatMasterParams represents possible parameters for the CatMasterReq +type CatMasterParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatMasterParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master.go new file mode 100644 index 0000000000..0ff98fbfd0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-master.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatMasterReq represent possible options for the /_cat/master request +type CatMasterReq struct { + Header http.Header + Params CatMasterParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatMasterReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/master", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatMasterResp represents the returned struct of the /_cat/master response +type CatMasterResp struct { + Master []CatMasterItemResp + response *opensearch.Response +} + +// CatMasterItemResp represents one index of the CatMasterResp +type CatMasterItemResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatMasterResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs-params.go new file mode 100644 index 0000000000..a53669ee64 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatNodeAttrsParams represents possible parameters for the CatNodeAttrsReq +type CatNodeAttrsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatNodeAttrsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs.go new file mode 100644 index 0000000000..3785893583 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodeattrs.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatNodeAttrsReq represent possible options for the /_cat/nodeattrs request +type CatNodeAttrsReq struct { + Header http.Header + Params CatNodeAttrsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatNodeAttrsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/nodeattrs", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatNodeAttrsResp represents the returned struct of the /_cat/nodeattrs response +type CatNodeAttrsResp struct { + NodeAttrs []CatNodeAttrsItemResp + response *opensearch.Response +} + +// CatNodeAttrsItemResp represents one index of the CatNodeAttrsResp +type CatNodeAttrsItemResp struct { + Node string `json:"node"` + ID string `json:"id"` + PID *int `json:"pid,string"` + Host string `json:"host"` + IP string `json:"ip"` + Port int `json:"port,string"` + Attr string `json:"attr"` + Value string `json:"value"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatNodeAttrsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes-params.go new file mode 100644 index 0000000000..3d13502be8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes-params.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatNodesParams represents possible parameters for the CatNodesReq +type CatNodesParams struct { + Bytes string + FullID *bool + H []string + IncludeUnloadedSegments *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatNodesParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.FullID != nil { + params["full_id"] = strconv.FormatBool(*r.FullID) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes.go new file mode 100644 index 0000000000..207431c061 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-nodes.go @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatNodesReq represent possible options for the /_cat/nodes request +type CatNodesReq struct { + Header http.Header + Params CatNodesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatNodesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/nodes", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatNodesResp represents the returned struct of the /_cat/nodes response +type CatNodesResp struct { + Nodes []CatNodesItemResp + response *opensearch.Response +} + +// CatNodesItemResp represents one index of the CatNodesResp +type CatNodesItemResp struct { + ID string `json:"id"` + PID *string `json:"pid"` + IP string `json:"ip"` + Port int `json:"port,string"` + HTTPAddress string `json:"http_address"` + Version string `json:"version"` + Type *string `json:"type"` + Build *string `json:"build"` + JDK *string `json:"jdk"` + DiskTotal *string `json:"disk.total"` + DiskUsed *string `json:"disk.used"` + DiskAvail *string `json:"disk.avail"` + DiskUsedPercent *string `json:"disk.used_percent"` + HeapCurrent *string `json:"heap.current"` + HeapPercent *int `json:"heap.percent,string"` + HeapMax *string `json:"heap.max"` + RAMCurrent *string `json:"ram.current"` + RAMPercent *int `json:"ram.percent,string"` + RAMMax *string `json:"ram.max"` + FileDescCurrent *int `json:"file_desc.current,string"` + FileDescPercent *int `json:"file_desc.percent,string"` + FileDescMax *int `json:"file_desc.max,string"` + CPU *int `json:"cpu,string"` + Load1M *string `json:"load_1m"` + Load5M *string `json:"load_5m"` + Load15M *string `json:"load_15m"` + Uptime *string `json:"uptime"` + Role string `json:"node.role"` + Roles string `json:"node.roles"` + Master string `json:"master"` + ClusterManager string `json:"cluster_manager"` + Name string `json:"name"` + CompletionSize *string `json:"completion.size"` + FieldDataMemorySize *string `json:"fielddata.memory_size"` + FileldDataEvictions *int `json:"fielddata.evictions,string"` + QueryCacheMemorySize *string `json:"query_cache.memory_size"` + QueryCacheEvictions *int `json:"query_cache.evictions,string"` + QueryCacheHitCount *int `json:"query_cache.hit_count,string"` + QueryCacheMissCount *int `json:"query_cache.miss_count,string"` + RequestCacheMemorySize *string `json:"request_cache.memory_size"` + RequestCacheEvictions *int `json:"request_cache.evictions,string"` + RequestCacheHitCount *int `json:"request_cache.hit_count,string"` + RequestCacheMissCount *int `json:"request_cache.miss_count,string"` + FlushTotal *int `json:"flush.total,string"` + FlushTotalTime *string `json:"flush.total_time"` + GetCurrent *int `json:"get.current,string"` + GetTime *string `json:"get.time"` + GetTotal *int `json:"get.total,string"` + GetExistsTime *string `json:"get.exists_time"` + GetExistsTotal *int `json:"get.exists_total,string"` + GetMissingTime *string `json:"get.missing_time"` + GetMissingTotal *int `json:"get.missing_total,string"` + IndexingDeleteCurrent *int `json:"indexing.delete_current,string"` + IndexingDeleteTime *string `json:"indexing.delete_time"` + IndexingDeleteTotal *int `json:"indexing.delete_total,string"` + IndexingIndexCurrent *int `json:"indexing.index_current,string"` + IndexingIndexTime *string `json:"indexing.index_time"` + IndexingIndexTotal *int `json:"indexing.index_total,string"` + IndexingIndexFailed *int `json:"indexing.index_failed,string"` + MergesCurrent *int `json:"merges.current,string"` + MergesCurrentDoc *int `json:"merges.current_docs,string"` + MergesCurrentSize *string `json:"merges.current_size"` + MergesTotal *int `json:"merges.total,string"` + MergesTotalDocs *int `json:"merges.total_docs,string"` + MergesTotalSize *string `json:"merges.total_size"` + MergesTotalTime *string `json:"merges.total_time"` + RefreshTotal *int `json:"refresh.total,string"` + RefreshTime *string `json:"refresh.time"` + RefreshExternalTotal *int `json:"refresh.external_total,string"` + RefreshExternalTime *string `json:"refresh.external_time"` + RefreshListeners *int `json:"refresh.listeners,string"` + ScriptCompilations *int `json:"script.compilations,string"` + ScriptCacheEvictions *int `json:"script.cache_evictions,string"` + ScriptCompilationLimitTriggered *int `json:"script.compilation_limit_triggered,string"` + SearchFetchCurrent *int `json:"search.fetch_current,string"` + SearchFetchTime *string `json:"search.fetch_time"` + SearchFetchTotal *int `json:"search.fetch_total,string"` + SearchOpenContexts *int `json:"search.open_contexts,string"` + SearchQueryCurrent *int `json:"search.query_current,string"` + SearchQueryTime *string `json:"search.query_time"` + SearchQueryTotal *int `json:"search.query_total,string"` + SearchConcurrentQueryCurrent *int `json:"search.concurrent_query_current,string"` + SearchConcurrentQueryTime *string `json:"search.concurrent_query_time"` + SearchConcurrentQueryTotal *int `json:"search.concurrent_query_total,string"` + SearchConcurrentAvgSliceCount *string `json:"search.concurrent_avg_slice_count"` + SearchScrollCurrent *int `json:"search.scroll_current,string"` + SearchScrollTime *string `json:"search.scroll_time"` + SearchScrollTotal *int `json:"search.scroll_total,string"` + SearchPointInTimeCurrent *int `json:"search.point_in_time_current,string"` + SearchPointInTimeTime *string `json:"search.point_in_time_time"` + SearchPointInTimeTotal *int `json:"search.point_in_time_total,string"` + SegmentsCount *int `json:"segments.count,string"` + SegmentsMemory *string `json:"segments.memory"` + SegmentsIndexWriteMemory *string `json:"segments.index_writer_memory"` + SegmentsVersionMapMemory *string `json:"segments.version_map_memory"` + SegmentsFixedBitsetMemory *string `json:"segments.fixed_bitset_memory"` + SuggestCurrent *int `json:"suggest.current,string"` + SuggestTime *string `json:"suggest.time"` + SuggestTotal *int `json:"suggest.total,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatNodesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks-params.go new file mode 100644 index 0000000000..db2aa45b96 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks-params.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatPendingTasksParams represents possible parameters for the CatPendingTasksReq +type CatPendingTasksParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatPendingTasksParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks.go new file mode 100644 index 0000000000..4c43cce8ab --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-pending_tasks.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatPendingTasksReq represent possible options for the /_cat/pending_tasks request +type CatPendingTasksReq struct { + Header http.Header + Params CatPendingTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatPendingTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/pending_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatPendingTasksResp represents the returned struct of the /_cat/pending_tasks response +type CatPendingTasksResp struct { + PendingTasks []CatPendingTaskResp + response *opensearch.Response +} + +// CatPendingTaskResp represents one index of the CatPendingTasksResp +type CatPendingTaskResp struct { + InsertOrder string `json:"insertOrder"` + TimeInQueue string `json:"timeInQueue"` + Priority string `json:"priority"` + Source string `json:"source"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatPendingTasksResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins-params.go new file mode 100644 index 0000000000..c7e06c0b56 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatPluginsParams represents possible parameters for the CatPluginsReq +type CatPluginsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatPluginsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins.go new file mode 100644 index 0000000000..08035c30dd --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-plugins.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatPluginsReq represent possible options for the /_cat/plugins request +type CatPluginsReq struct { + Header http.Header + Params CatPluginsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatPluginsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/plugins", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatPluginsResp represents the returned struct of the /_cat/plugins response +type CatPluginsResp struct { + Plugins []CatPluginResp + response *opensearch.Response +} + +// CatPluginResp represents one index of the CatPluginsResp +type CatPluginResp struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Component string `json:"component,omitempty"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatPluginsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery-params.go new file mode 100644 index 0000000000..6cdacbd7f2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery-params.go @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatRecoveryParams represents possible parameters for the CatRecoveryReq +type CatRecoveryParams struct { + ActiveOnly *bool + Bytes string + Detailed *bool + H []string + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatRecoveryParams) get() map[string]string { + params := make(map[string]string) + + if r.ActiveOnly != nil { + params["active_only"] = strconv.FormatBool(*r.ActiveOnly) + } + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery.go new file mode 100644 index 0000000000..c71c536a7a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-recovery.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatRecoveryReq represent possible options for the /_cat/recovery request +type CatRecoveryReq struct { + Indices []string + Header http.Header + Params CatRecoveryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatRecoveryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/recovery/") + len(indices)) + path.WriteString("/_cat/recovery") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatRecoveryResp represents the returned struct of the /_cat/recovery response +type CatRecoveryResp struct { + Recovery []CatRecoveryItemResp + response *opensearch.Response +} + +// CatRecoveryItemResp represents one index of the CatRecoveryResp +type CatRecoveryItemResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + StartTime string `json:"start_time"` + StartTimeMillis int `json:"start_time_millis,string"` + StopTime string `json:"stop_time"` + StopTimeMillis int `json:"stop_time_millis,string"` + Time string `json:"time"` + Type string `json:"type"` + Stage string `json:"stage"` + SourceHost string `json:"source_host"` + SourceNode string `json:"source_node"` + TargetHost string `json:"target_host"` + TargetNode string `json:"target_node"` + Repository string `json:"repository"` + Snapshot string `json:"snapshot"` + Files int `json:"files,string"` + FilesRecovered int `json:"files_recovered,string"` + FilesPercent string `json:"files_percent"` + FilesTotal int `json:"files_total,string"` + Bytes string `json:"bytes"` + BytesRecovered string `json:"bytes_recovered"` + BytesPercent string `json:"bytes_percent"` + BytesTotal string `json:"bytes_total"` + TranslogOps int `json:"translog_ops,string"` + TranslogOpsRecovered int `json:"translog_ops_recovered,string"` + TranslogOpsPercent string `json:"translog_ops_percent"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatRecoveryResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories-params.go new file mode 100644 index 0000000000..75aeb0c058 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatRepositoriesParams represents possible parameters for the CatRepositoriesReq +type CatRepositoriesParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatRepositoriesParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories.go new file mode 100644 index 0000000000..35417890d3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-repositories.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatRepositoriesReq represent possible options for the /_cat/repositories request +type CatRepositoriesReq struct { + Header http.Header + Params CatRepositoriesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatRepositoriesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/repositories", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatRepositoriesResp represents the returned struct of the /_cat/repositories response +type CatRepositoriesResp struct { + Repositories []CatRepositorieResp + response *opensearch.Response +} + +// CatRepositorieResp represents one index of the CatRepositoriesResp +type CatRepositorieResp struct { + ID string `json:"id"` + Type string `json:"type"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatRepositoriesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments-params.go new file mode 100644 index 0000000000..4880a13416 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments-params.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatSegmentsParams represents possible parameters for the CatSegmentsReq +type CatSegmentsParams struct { + Bytes string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatSegmentsParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments.go new file mode 100644 index 0000000000..b4d6685a65 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-segments.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatSegmentsReq represent possible options for the /_cat/segments request +type CatSegmentsReq struct { + Indices []string + Header http.Header + Params CatSegmentsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatSegmentsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/segments/") + len(indices)) + path.WriteString("/_cat/segments") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatSegmentsResp represents the returned struct of the /_cat/segments response +type CatSegmentsResp struct { + Segments []CatSegmentResp + response *opensearch.Response +} + +// CatSegmentResp represents one index of the CatSegmentsResp +type CatSegmentResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + Prirep string `json:"prirep"` + IP string `json:"ip"` + ID string `json:"id"` + Segment string `json:"segment"` + Generation int `json:"generation,string"` + DocsCount int `json:"docs.count,string"` + DocsDeleted int `json:"docs.deleted,string"` + Size string `json:"size"` + SizeMemory string `json:"size.memory"` + Committed bool `json:"committed,string"` + Searchable bool `json:"searchable,string"` + Version string `json:"version"` + Compound bool `json:"compound,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatSegmentsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards-params.go new file mode 100644 index 0000000000..7abd13fdb9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards-params.go @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatShardsParams represents possible parameters for the CatShardsReq +type CatShardsParams struct { + Bytes string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatShardsParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards.go new file mode 100644 index 0000000000..bcbb1ef3e7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-shards.go @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatShardsReq represent possible options for the /_cat/shards request +type CatShardsReq struct { + Indices []string + Header http.Header + Params CatShardsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatShardsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/shards/") + len(indices)) + path.WriteString("/_cat/shards") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatShardsResp represents the returned struct of the /_cat/shards response +type CatShardsResp struct { + Shards []CatShardResp + response *opensearch.Response +} + +// CatShardResp represents one index of the CatShardsResp +type CatShardResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + Prirep string `json:"prirep"` + State string `json:"state"` + Docs *string `json:"docs"` + Store *string `json:"store"` + IP *string `json:"ip"` + ID *string `json:"id"` + Node *string `json:"node"` + SyncID *string `json:"sync_id"` + UnassignedReason *string `json:"unassigned.reason"` + UnassignedAt *string `json:"unassigned.at"` + UnassignedFor *string `json:"unassigned.for"` + UnassignedDetails *string `json:"unassigned.details"` + RecoverysourceType *string `json:"recoverysource.type"` + CompletionSize *string `json:"completion.size"` + FielddataMemorySize *string `json:"fielddata.memory_size"` + FielddataEvictions *int `json:"fielddata.evictions,string"` + QueryCacheMemorySize *string `json:"query_cache.memory_size"` + QueryCacheEvictions *int `json:"query_cache.evictions,string"` + FlushTotal *int `json:"flush.total,string"` + FlushTotalTime *string `json:"flush.total_time"` + GetCurrent *int `json:"get.current,string"` + GetTime *string `json:"get.time"` + GetTotal *int `json:"get.total,string"` + GetExistsTime *string `json:"get.exists_time"` + GetExistsTotal *int `json:"get.exists_total,string"` + GetMissingTime *string `json:"get.missing_time"` + GetMissingTotal *int `json:"get.missing_total,string"` + IndexingDeleteCurrent *int `json:"indexing.delete_current,string"` + IndexingDeleteTime *string `json:"indexing.delete_time"` + IndexingDeleteTotal *string `json:"indexing.delete_total"` + IndexingIndexCurrent *int `json:"indexing.index_current,string"` + IndexingIndexTime *string `json:"indexing.index_time"` + IndexingIndexTotal *int `json:"indexing.index_total,string"` + IndexingIndexFailed *int `json:"indexing.index_failed,string"` + MergesCurrent *int `json:"merges.current,string"` + MergesCurrentDocs *int `json:"merges.current_docs,string"` + MergesCurrentSize *string `json:"merges.current_size"` + MergesTotal *int `json:"merges.total,string"` + MergesTotalDocs *int `json:"merges.total_docs,string"` + MergesTotalSize *string `json:"merges.total_size"` + MergesTotalTime *string `json:"merges.total_time"` + RefreshTotal *int `json:"refresh.total,string"` + RefreshTime *string `json:"refresh.time"` + RefreshExternalTotal *int `json:"refresh.external_total,string"` + RefreshExternalTime *string `json:"refresh.external_time"` + RefreshListeners *int `json:"refresh.listeners,string"` + SearchFetchCurrent *int `json:"search.fetch_current,string"` + SearchFetchTime *string `json:"search.fetch_time"` + SearchFetchTotal *int `json:"search.fetch_total,string"` + SearchOpenContexts *int `json:"search.open_contexts,string"` + SearchQueryCurrent *int `json:"search.query_current,string"` + SearchQueryTime *string `json:"search.query_time"` + SearchQueryTotal *int `json:"search.query_total,string"` + SearchConcurrentQueryCurrent *int `json:"search.concurrent_query_current,string"` + SearchConcurrentQueryTime *string `json:"search.concurrent_query_time"` + SearchConcurrentQueryTotal *int `json:"search.concurrent_query_total,string"` + SearchConcurrentAvgSliceCount *string `json:"search.concurrent_avg_slice_count"` + SearchScrollCurrent *int `json:"search.scroll_current,string"` + SearchScrollTime *string `json:"search.scroll_time"` + SearchScrollTotal *int `json:"search.scroll_total,string"` + SearchPointInTimeCurrent *int `json:"search.point_in_time_current,string"` + SearchPointInTimeTime *string `json:"search.point_in_time_time"` + SearchPointInTimeTotal *int `json:"search.point_in_time_total,string"` + SearchIdleReactivateCountTotal *int `json:"search.search_idle_reactivate_count_total,string"` + SegmentsCount *int `json:"segments.count,string"` + SegmentsMemory *string `json:"segments.memory"` + SegmentsIndexWriterMemory *string `json:"segments.index_writer_memory"` + SegmentsVersionMapMemory *string `json:"segments.version_map_memory"` + SegmentsFixedBitsetMemory *string `json:"segments.fixed_bitset_memory"` + SeqNoMax *int `json:"seq_no.max,string"` + SeqNoLocalCheckpoint *int `json:"seq_no.local_checkpoint,string"` + SeqNoGlobalCheckpoint *int `json:"seq_no.global_checkpoint,string"` + WarmerCurrent *int `json:"warmer.current,string"` + WarmerTotal *int `json:"warmer.total,string"` + WarmerTotalTime *string `json:"warmer.total_time"` + PathData *string `json:"path.data"` + PathState *string `json:"path.state"` + DocsDeleted *int `json:"docs.deleted,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatShardsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots-params.go new file mode 100644 index 0000000000..b7351262ba --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots-params.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatSnapshotsParams represents possible parameters for the CatSnapshotsReq +type CatSnapshotsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatSnapshotsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots.go new file mode 100644 index 0000000000..76c64854f1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-snapshots.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatSnapshotsReq represent possible options for the /_cat/snapshots request +type CatSnapshotsReq struct { + Repository string + Header http.Header + Params CatSnapshotsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatSnapshotsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("%s%s", "/_cat/snapshots/", r.Repository), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatSnapshotsResp represents the returned struct of the /_cat/snapshots response +type CatSnapshotsResp struct { + Snapshots []CatSnapshotResp + response *opensearch.Response +} + +// CatSnapshotResp represents one index of the CatSnapshotsResp +type CatSnapshotResp struct { + ID string `json:"id"` + Status string `json:"status"` + StartEpoch int `json:"start_epoch,string"` + StartTime string `json:"start_time"` + EndEpoch int `json:"end_epoch,string"` + EndTime string `json:"end_time"` + Duration string `json:"duration"` + Indices int `json:"indices,string"` + SuccessfulShards int `json:"successful_shards,string"` + FailedShards int `json:"failed_shards,string"` + TotalShards int `json:"total_shards,string"` + Reason string `json:"reason"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatSnapshotsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks-params.go new file mode 100644 index 0000000000..a209dd292e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks-params.go @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatTasksParams represents possible parameters for the CatTasksReq +type CatTasksParams struct { + Actions []string + Detailed *bool + H []string + Nodes []string + ParentTaskID string + Local *bool + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatTasksParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks.go new file mode 100644 index 0000000000..5eecade16c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-tasks.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatTasksReq represent possible options for the /_cat/tasks request +type CatTasksReq struct { + Header http.Header + Params CatTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatTasksResp represents the returned struct of the /_cat/tasks response +type CatTasksResp struct { + Tasks []CatTaskResp + response *opensearch.Response +} + +// CatTaskResp represents one index of the CatTasksResp +type CatTaskResp struct { + ID string `json:"id"` + Action string `json:"action"` + TaskID string `json:"task_id"` + ParentTaskID string `json:"parent_task_id"` + Type string `json:"type"` + StartTime int `json:"start_time,string"` + Timestamp string `json:"timestamp"` + RunningTimeNs int `json:"running_time_ns,string"` + RunningTime string `json:"running_time"` + NodeID string `json:"node_id"` + IP string `json:"ip"` + Port int `json:"port,string"` + Node string `json:"node"` + Version string `json:"version"` + XOpaqueID string `json:"x_opaque_id"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatTasksResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates-params.go new file mode 100644 index 0000000000..573c203a11 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatTemplatesParams represents possible parameters for the CatTemplatesReq +type CatTemplatesParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatTemplatesParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates.go new file mode 100644 index 0000000000..07b0db5f30 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-templates.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatTemplatesReq represent possible options for the /_cat/templates request +type CatTemplatesReq struct { + Templates []string + Header http.Header + Params CatTemplatesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatTemplatesReq) GetRequest() (*http.Request, error) { + templates := strings.Join(r.Templates, ",") + var path strings.Builder + path.Grow(len("/_cat/templates/") + len(templates)) + path.WriteString("/_cat/templates") + if len(r.Templates) > 0 { + path.WriteString("/") + path.WriteString(templates) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatTemplatesResp represents the returned struct of the /_cat/templates response +type CatTemplatesResp struct { + Templates []CatTemplateResp + response *opensearch.Response +} + +// CatTemplateResp represents one index of the CatTemplatesResp +type CatTemplateResp struct { + Name string `json:"name"` + IndexPatterns string `json:"index_patterns"` + Order int `json:"order,string"` + Version *string `json:"version"` + ComposedOf string `json:"composed_of"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatTemplatesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool-params.go new file mode 100644 index 0000000000..3dcb9bf2e3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatThreadPoolParams represents possible parameters for the CatThreadPoolReq +type CatThreadPoolParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r CatThreadPoolParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + params["format"] = "json" + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool.go new file mode 100644 index 0000000000..37c29e5f0f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat-thread_pool.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// CatThreadPoolReq represent possible options for the /_cat/thread_pool request +type CatThreadPoolReq struct { + Pools []string + Header http.Header + Params CatThreadPoolParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatThreadPoolReq) GetRequest() (*http.Request, error) { + pools := strings.Join(r.Pools, ",") + var path strings.Builder + path.Grow(len("/_cat/thread_pool/") + len(pools)) + path.WriteString("/_cat/thread_pool") + if len(r.Pools) > 0 { + path.WriteString("/") + path.WriteString(pools) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatThreadPoolResp represents the returned struct of the /_cat/thread_pool response +type CatThreadPoolResp struct { + ThreadPool []CatThreadPoolItemResp + response *opensearch.Response +} + +// CatThreadPoolItemResp represents one index of the CatThreadPoolResp +type CatThreadPoolItemResp struct { + NodeName string `json:"node_name"` + NodeID string `json:"node_id"` + EphemeralNodeID string `json:"ephemeral_node_id"` + PID int `json:"pid,string"` + Host string `json:"host"` + IP string `json:"ip"` + Port int `json:"port,string"` + Name string `json:"name"` + Type string `json:"type"` + Active int `json:"active,string"` + PoolSize int `json:"pool_size,string"` + Queue int `json:"queue,string"` + QueueSize int `json:"queue_size,string"` + Rejected int `json:"rejected,string"` + Largest int `json:"largest,string"` + Completed int `json:"completed,string"` + Core *int `json:"core,string"` + Max *int `json:"max,string"` + Size *int `json:"size,string"` + KeepAlive *string `json:"keep_alive"` + TotalWaitTime string `json:"total_wait_time"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatThreadPoolResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat.go new file mode 100644 index 0000000000..7ddd0f4aac --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cat.go @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type catClient struct { + apiClient *Client +} + +// Aliases executes a /_cat/aliases request with the optional CatAliasesReq +func (c catClient) Aliases(ctx context.Context, req *CatAliasesReq) (*CatAliasesResp, error) { + if req == nil { + req = &CatAliasesReq{} + } + + var ( + data CatAliasesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Aliases); err != nil { + return &data, err + } + + return &data, nil +} + +// Allocation executes a /_cat/allocation request with the optional CatAllocationReq +func (c catClient) Allocation(ctx context.Context, req *CatAllocationReq) (*CatAllocationsResp, error) { + if req == nil { + req = &CatAllocationReq{} + } + + var ( + data CatAllocationsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Allocations); err != nil { + return &data, err + } + + return &data, nil +} + +// ClusterManager executes a /_cat/cluster_manager request with the optional CatClusterManagerReq +func (c catClient) ClusterManager(ctx context.Context, req *CatClusterManagerReq) (*CatClusterManagersResp, error) { + if req == nil { + req = &CatClusterManagerReq{} + } + + var ( + data CatClusterManagersResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.ClusterManagers); err != nil { + return &data, err + } + + return &data, nil +} + +// Count executes a /_cat/count request with the optional CatCountReq +func (c catClient) Count(ctx context.Context, req *CatCountReq) (*CatCountsResp, error) { + if req == nil { + req = &CatCountReq{} + } + + var ( + data CatCountsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Counts); err != nil { + return &data, err + } + + return &data, nil +} + +// FieldData executes a /_cat/fielddata request with the optional CatFieldDataReq +func (c catClient) FieldData(ctx context.Context, req *CatFieldDataReq) (*CatFieldDataResp, error) { + if req == nil { + req = &CatFieldDataReq{} + } + + var ( + data CatFieldDataResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.FieldData); err != nil { + return &data, err + } + + return &data, nil +} + +// Health executes a /_cat/health request with the optional CatHealthReq +func (c catClient) Health(ctx context.Context, req *CatHealthReq) (*CatHealthResp, error) { + if req == nil { + req = &CatHealthReq{} + } + + var ( + data CatHealthResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Health); err != nil { + return &data, err + } + + return &data, nil +} + +// Indices executes a /_cat/indices request with the optional CatIndicesReq +func (c catClient) Indices(ctx context.Context, req *CatIndicesReq) (*CatIndicesResp, error) { + if req == nil { + req = &CatIndicesReq{} + } + + var ( + data CatIndicesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Master executes a /_cat/master request with the optional CatMasterReq +func (c catClient) Master(ctx context.Context, req *CatMasterReq) (*CatMasterResp, error) { + if req == nil { + req = &CatMasterReq{} + } + + var ( + data CatMasterResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Master); err != nil { + return &data, err + } + + return &data, nil +} + +// NodeAttrs executes a /_cat/nodeattrs request with the optional CatNodeAttrsReq +func (c catClient) NodeAttrs(ctx context.Context, req *CatNodeAttrsReq) (*CatNodeAttrsResp, error) { + if req == nil { + req = &CatNodeAttrsReq{} + } + + var ( + data CatNodeAttrsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.NodeAttrs); err != nil { + return &data, err + } + + return &data, nil +} + +// Nodes executes a /_cat/nodes request with the optional CatNodesReq +func (c catClient) Nodes(ctx context.Context, req *CatNodesReq) (*CatNodesResp, error) { + if req == nil { + req = &CatNodesReq{} + } + + var ( + data CatNodesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Nodes); err != nil { + return &data, err + } + + return &data, nil +} + +// PendingTasks executes a /_cat/pending_tasks request with the optional CatPendingTasksReq +func (c catClient) PendingTasks(ctx context.Context, req *CatPendingTasksReq) (*CatPendingTasksResp, error) { + if req == nil { + req = &CatPendingTasksReq{} + } + + var ( + data CatPendingTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.PendingTasks); err != nil { + return &data, err + } + + return &data, nil +} + +// Plugins executes a /_cat/plugins request with the optional CatPluginsReq +func (c catClient) Plugins(ctx context.Context, req *CatPluginsReq) (*CatPluginsResp, error) { + if req == nil { + req = &CatPluginsReq{} + } + + var ( + data CatPluginsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Plugins); err != nil { + return &data, err + } + + return &data, nil +} + +// Recovery executes a /_cat/recovery request with the optional CatRecoveryReq +func (c catClient) Recovery(ctx context.Context, req *CatRecoveryReq) (*CatRecoveryResp, error) { + if req == nil { + req = &CatRecoveryReq{} + } + + var ( + data CatRecoveryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Recovery); err != nil { + return &data, err + } + + return &data, nil +} + +// Repositories executes a /_cat/repositories request with the optional CatRepositoriesReq +func (c catClient) Repositories(ctx context.Context, req *CatRepositoriesReq) (*CatRepositoriesResp, error) { + if req == nil { + req = &CatRepositoriesReq{} + } + + var ( + data CatRepositoriesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Repositories); err != nil { + return &data, err + } + + return &data, nil +} + +// Segments executes a /_cat/segments request with the optional CatSegmentsReq +func (c catClient) Segments(ctx context.Context, req *CatSegmentsReq) (*CatSegmentsResp, error) { + if req == nil { + req = &CatSegmentsReq{} + } + + var ( + data CatSegmentsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Segments); err != nil { + return &data, err + } + + return &data, nil +} + +// Shards executes a /_cat/shards request with the optional CatShardsReq +func (c catClient) Shards(ctx context.Context, req *CatShardsReq) (*CatShardsResp, error) { + if req == nil { + req = &CatShardsReq{} + } + + var ( + data CatShardsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Shards); err != nil { + return &data, err + } + + return &data, nil +} + +// Snapshots executes a /_cat/snapshots request with the required CatSnapshotsReq +func (c catClient) Snapshots(ctx context.Context, req CatSnapshotsReq) (*CatSnapshotsResp, error) { + var ( + data CatSnapshotsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Snapshots); err != nil { + return &data, err + } + + return &data, nil +} + +// Tasks executes a /_cat/tasks request with the optional CatTasksReq +func (c catClient) Tasks(ctx context.Context, req *CatTasksReq) (*CatTasksResp, error) { + if req == nil { + req = &CatTasksReq{} + } + + var ( + data CatTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Tasks); err != nil { + return &data, err + } + + return &data, nil +} + +// Templates executes a /_cat/templates request with the optional CatTemplatesReq +func (c catClient) Templates(ctx context.Context, req *CatTemplatesReq) (*CatTemplatesResp, error) { + if req == nil { + req = &CatTemplatesReq{} + } + + var ( + data CatTemplatesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Templates); err != nil { + return &data, err + } + + return &data, nil +} + +// ThreadPool executes a /_cat/thread_pool request with the optional CatThreadPoolReq +func (c catClient) ThreadPool(ctx context.Context, req *CatThreadPoolReq) (*CatThreadPoolResp, error) { + if req == nil { + req = &CatThreadPoolReq{} + } + + var ( + data CatThreadPoolResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.ThreadPool); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain-params.go new file mode 100644 index 0000000000..b0ac3e2f7d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// ClusterAllocationExplainParams represents possible parameters for the ClusterAllocationExplainReq +type ClusterAllocationExplainParams struct { + IncludeDiskInfo *bool + IncludeYesDecisions *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterAllocationExplainParams) get() map[string]string { + params := make(map[string]string) + + if r.IncludeDiskInfo != nil { + params["include_disk_info"] = strconv.FormatBool(*r.IncludeDiskInfo) + } + + if r.IncludeYesDecisions != nil { + params["include_yes_decisions"] = strconv.FormatBool(*r.IncludeYesDecisions) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain.go new file mode 100644 index 0000000000..b446fe4734 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-allocation_explain.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterAllocationExplainReq represents possible options for the /_nodes request +type ClusterAllocationExplainReq struct { + Body *ClusterAllocationExplainBody + Header http.Header + Params ClusterAllocationExplainParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterAllocationExplainReq) GetRequest() (*http.Request, error) { + var reader io.Reader + + if r.Body != nil { + body, err := json.Marshal(r.Body) + if err != nil { + return nil, err + } + + reader = bytes.NewReader(body) + } + + return opensearch.BuildRequest( + "GET", + "/_cluster/allocation/explain", + reader, + r.Params.get(), + r.Header, + ) +} + +// ClusterAllocationExplainBody represents the optional Body for the ClusterAllocationExplainReq +type ClusterAllocationExplainBody struct { + Index string `json:"index"` + Shard int `json:"shard"` + Primary bool `json:"primary"` +} + +// ClusterAllocationExplainResp represents the returned struct of the /_nodes response +type ClusterAllocationExplainResp struct { + Index string `json:"index"` + Shard int `json:"shard"` + Primary bool `json:"primary"` + CurrentState string `json:"current_state"` + CurrentNode ClusterAllocationCurrentNode `json:"current_node"` + UnassignedInfo struct { + Reason string `json:"reason"` + At string `json:"at"` + LastAllocationStatus string `json:"last_allocation_status"` + } `json:"unassigned_info"` + CanAllocate string `json:"can_allocate"` + CanRemainOnCurrentNode string `json:"can_remain_on_current_node"` + CanRebalanceCluster string `json:"can_rebalance_cluster"` + CanRebalanceToOtherNode string `json:"can_rebalance_to_other_node"` + RebalanceExplanation string `json:"rebalance_explanation"` + AllocateExplanation string `json:"allocate_explanation"` + NodeAllocationDecisions []ClusterAllocationNodeDecisions `json:"node_allocation_decisions"` + CanRebalanceClusterDecisions []ClusterAllocationExplainDeciders `json:"can_rebalance_cluster_decisions"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterAllocationExplainResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterAllocationCurrentNode is a sub type of ClusterAllocationExplainResp containing information of the node the shard is on +type ClusterAllocationCurrentNode struct { + NodeID string `json:"id"` + NodeName string `json:"name"` + TransportAddress string `json:"transport_address"` + NodeAttributes struct { + ShardIndexingPressureEnabled string `json:"shard_indexing_pressure_enabled"` + } `json:"attributes"` + WeightRanking int `json:"weight_ranking"` +} + +// ClusterAllocationNodeDecisions is a sub type of ClusterAllocationExplainResp containing information of a node allocation decission +type ClusterAllocationNodeDecisions struct { + NodeID string `json:"node_id"` + NodeName string `json:"node_name"` + TransportAddress string `json:"transport_address"` + NodeAttributes struct { + ShardIndexingPressureEnabled string `json:"shard_indexing_pressure_enabled"` + } `json:"node_attributes"` + NodeDecision string `json:"node_decision"` + WeightRanking int `json:"weight_ranking"` + Deciders []ClusterAllocationExplainDeciders `json:"deciders"` +} + +// ClusterAllocationExplainDeciders is a sub type of ClusterAllocationExplainResp and +// ClusterAllocationNodeDecisions containing inforamtion about Deciders decissions +type ClusterAllocationExplainDeciders struct { + Decider string `json:"decider"` + Decision string `json:"decision"` + Explanation string `json:"explanation"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission-params.go new file mode 100644 index 0000000000..b88f30fca5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission-params.go @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ClusterPutDecommissionParams represents possible parameters for the ClusterPutDecommissionReq +type ClusterPutDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterPutDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// ClusterGetDecommissionParams represents possible parameters for the ClusterGetDecommissionReq +type ClusterGetDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterGetDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// ClusterDeleteDecommissionParams represents possible parameters for the ClusterDeleteDecommissionReq +type ClusterDeleteDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterDeleteDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission.go new file mode 100644 index 0000000000..d0f99bb6f8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-decommission.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterPutDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterPutDecommissionReq struct { + AwarenessAttrName string + AwarenessAttrValue string + + Header http.Header + Params ClusterPutDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPutDecommissionReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(34 + len(r.AwarenessAttrName) + len(r.AwarenessAttrValue)) + path.WriteString("/_cluster/decommission/awareness/") + path.WriteString(r.AwarenessAttrName) + path.WriteString("/") + path.WriteString(r.AwarenessAttrValue) + + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterPutDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterPutDecommissionResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPutDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterDeleteDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterDeleteDecommissionReq struct { + Header http.Header + Params ClusterDeleteDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterDeleteDecommissionReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + "/_cluster/decommission/awareness", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterDeleteDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterDeleteDecommissionResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterDeleteDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterGetDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterGetDecommissionReq struct { + AwarenessAttrName string + + Header http.Header + Params ClusterGetDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterGetDecommissionReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(41 + len(r.AwarenessAttrName)) + path.WriteString("/_cluster/decommission/awareness/") + path.WriteString(r.AwarenessAttrName) + path.WriteString("/_status") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterGetDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterGetDecommissionResp struct { + Values map[string]string + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterGetDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health-params.go new file mode 100644 index 0000000000..1447335732 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health-params.go @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterHealthParams represents possible parameters for the ClusterHealthReq +type ClusterHealthParams struct { + ExpandWildcards string + Level string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + WaitForEvents string + WaitForNoInitializingShards *bool + WaitForNoRelocatingShards *bool + WaitForNodes string + WaitForStatus string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterHealthParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Level != "" { + params["level"] = r.Level + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForEvents != "" { + params["wait_for_events"] = r.WaitForEvents + } + + if r.WaitForNoInitializingShards != nil { + params["wait_for_no_initializing_shards"] = strconv.FormatBool(*r.WaitForNoInitializingShards) + } + + if r.WaitForNoRelocatingShards != nil { + params["wait_for_no_relocating_shards"] = strconv.FormatBool(*r.WaitForNoRelocatingShards) + } + + if r.WaitForNodes != "" { + params["wait_for_nodes"] = r.WaitForNodes + } + + if r.WaitForStatus != "" { + params["wait_for_status"] = r.WaitForStatus + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health.go new file mode 100644 index 0000000000..aa8984132d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-health.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterHealthReq represents possible options for the /_cluster/health request +type ClusterHealthReq struct { + Indices []string + Header http.Header + Params ClusterHealthParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterHealthReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(17 + len(indices)) + path.WriteString("/_cluster/health") + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterHealthResp represents the returned struct of the ClusterHealthReq response +type ClusterHealthResp struct { + ClusterName string `json:"cluster_name"` + Status string `json:"status"` + TimedOut bool `json:"timed_out"` + NumberOfNodes int `json:"number_of_nodes"` + NumberOfDataNodes int `json:"number_of_data_nodes"` + DiscoveredMaster bool `json:"discovered_master"` + DiscoveredClusterManager bool `json:"discovered_cluster_manager"` + ActivePrimaryShards int `json:"active_primary_shards"` + ActiveShards int `json:"active_shards"` + RelocatingShards int `json:"relocating_shards"` + InitializingShards int `json:"initializing_shards"` + UnassignedShards int `json:"unassigned_shards"` + DelayedUnassignedShards int `json:"delayed_unassigned_shards"` + NumberOfPendingTasks int `json:"number_of_pending_tasks"` + NumberOfInFlightFetch int `json:"number_of_in_flight_fetch"` + TaskMaxWaitingInQueueMillis int `json:"task_max_waiting_in_queue_millis"` + ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterHealthResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks-params.go new file mode 100644 index 0000000000..7deda2a1db --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterPendingTasksParams represents possible parameters for the ClusterPendingTasksReq +type ClusterPendingTasksParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterPendingTasksParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks.go new file mode 100644 index 0000000000..ba26216c3c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-pending_tasks.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterPendingTasksReq represents possible options for the /_cluster/pending_tasks request +type ClusterPendingTasksReq struct { + Header http.Header + Params ClusterPendingTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPendingTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cluster/pending_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterPendingTasksResp represents the returned struct of the ClusterPendingTasksReq response +type ClusterPendingTasksResp struct { + Tasks []ClusterPendingTasksItem `json:"tasks"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPendingTasksResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterPendingTasksItem is a sub type if ClusterPendingTasksResp containing information about a task +type ClusterPendingTasksItem struct { + InsertOrder int `json:"insert_order"` + Priority string `json:"priority"` + Source string `json:"source"` + TimeInQueueMillis int `json:"time_in_queue_millis"` + TimeInQueue string `json:"time_in_queue"` + Executing bool `json:"executing"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info-params.go new file mode 100644 index 0000000000..52118acf45 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ClusterRemoteInfoParams represents possible parameters for the ClusterRemoteInfoReq +type ClusterRemoteInfoParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterRemoteInfoParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info.go new file mode 100644 index 0000000000..af74f8d586 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-remote_info.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterRemoteInfoReq represents possible options for the /_remote/info request +type ClusterRemoteInfoReq struct { + Header http.Header + Params ClusterRemoteInfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterRemoteInfoReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_remote/info", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterRemoteInfoResp represents the returned struct of the ClusterRemoteInfoReq response +type ClusterRemoteInfoResp struct { + Clusters map[string]ClusterRemoteInfoDetails + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterRemoteInfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterRemoteInfoDetails is a sub type of ClusterRemoteInfoResp contains information about a remote connection +type ClusterRemoteInfoDetails struct { + Connected bool `json:"connected"` + Mode string `json:"mode"` + Seeds []string `json:"seeds"` + NumNodesConnected int `json:"num_nodes_connected"` + MaxConnectionsPerCluster int `json:"max_connections_per_cluster"` + InitialConnectTimeout string `json:"initial_connect_timeout"` + SkipUnavailable bool `json:"skip_unavailable"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute-params.go new file mode 100644 index 0000000000..340f659fc4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterRerouteParams represents possible parameters for the ClusterRerouteReq +type ClusterRerouteParams struct { + DryRun *bool + Explain *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Metric []string + RetryFailed *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterRerouteParams) get() map[string]string { + params := make(map[string]string) + + if r.DryRun != nil { + params["dry_run"] = strconv.FormatBool(*r.DryRun) + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Metric) > 0 { + params["metric"] = strings.Join(r.Metric, ",") + } + + if r.RetryFailed != nil { + params["retry_failed"] = strconv.FormatBool(*r.RetryFailed) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute.go new file mode 100644 index 0000000000..113e12b111 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-reroute.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterRerouteReq represents possible options for the /_cluster/reroute request +type ClusterRerouteReq struct { + Body io.Reader + + Header http.Header + Params ClusterRerouteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterRerouteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_cluster/reroute", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ClusterRerouteResp represents the returned struct of the ClusterRerouteReq response +type ClusterRerouteResp struct { + Acknowledged bool `json:"acknowledged"` + State ClusterRerouteState `json:"state"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterRerouteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterRerouteState is a sub type of ClusterRerouteResp containing information about the cluster and cluster routing +type ClusterRerouteState struct { + ClusterUUID string `json:"cluster_uuid"` + Version int `json:"version"` + StateUUID string `json:"state_uuid"` + MasterNode string `json:"master_node"` + ClusterManagerNode string `json:"cluster_manager_node"` + Blocks json.RawMessage `json:"blocks"` + Nodes map[string]ClusterStateNodes `json:"nodes"` + RoutingTable struct { + Indices map[string]struct { + Shards map[string][]ClusterStateRoutingIndex `json:"shards"` + } `json:"indices"` + } `json:"routing_table"` + RoutingNodes ClusterStateRoutingNodes `json:"routing_nodes"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` + SnapshotDeletions struct { + SnapshotDeletions []json.RawMessage `json:"snapshot_deletions"` + } `json:"snapshot_deletions"` + Snapshots struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"snapshots"` + Restore struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"restore"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings-params.go new file mode 100644 index 0000000000..5241561db1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings-params.go @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterGetSettingsParams represents possible parameters for the ClusterGetSettingsReq +type ClusterGetSettingsParams struct { + FlatSettings *bool + IncludeDefaults *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterGetSettingsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// ClusterPutSettingsParams represents possible parameters for the ClusterGetSettingsReq +type ClusterPutSettingsParams struct { + FlatSettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterPutSettingsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings.go new file mode 100644 index 0000000000..dc1e5ee0a8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-settings.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterGetSettingsReq represents possible options for the /_cluster/settings request +type ClusterGetSettingsReq struct { + Header http.Header + Params ClusterGetSettingsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterGetSettingsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cluster/settings", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterGetSettingsResp represents the returned struct of the ClusterGetSettingsReq response +type ClusterGetSettingsResp struct { + Persistent json.RawMessage `json:"persistent"` + Transient json.RawMessage `json:"transient"` + Defaults json.RawMessage `json:"defaults"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterGetSettingsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterPutSettingsReq represents possible options for the /_cluster/settings request +type ClusterPutSettingsReq struct { + Body io.Reader + Header http.Header + Params ClusterPutSettingsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPutSettingsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + "/_cluster/settings", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ClusterPutSettingsResp represents the returned struct of the /_cluster/settings response +type ClusterPutSettingsResp struct { + Acknowledged bool `json:"acknowledged"` + Persistent json.RawMessage `json:"persistent"` + Transient json.RawMessage `json:"transient"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPutSettingsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state-params.go new file mode 100644 index 0000000000..12e63cc52d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state-params.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterStateParams represents possible parameters for the ClusterStateReq +type ClusterStateParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForMetadataVersion *int + WaitForTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterStateParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForMetadataVersion != nil { + params["wait_for_metadata_version"] = strconv.FormatInt(int64(*r.WaitForMetadataVersion), 10) + } + + if r.WaitForTimeout != 0 { + params["wait_for_timeout"] = formatDuration(r.WaitForTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state.go new file mode 100644 index 0000000000..096f3fb07f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-state.go @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterStateReq represents possible options for the /_cluster/state request +type ClusterStateReq struct { + Metrics []string + Indices []string + + Header http.Header + Params ClusterStateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterStateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + path.Grow(17 + len(indices) + len(metrics)) + path.WriteString("/_cluster/state") + if len(metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterStateResp represents the returned struct of the ClusterStateReq response +type ClusterStateResp struct { + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Version int `json:"version"` + StateUUID string `json:"state_uuid"` + MasterNode string `json:"master_node"` + ClusterManagerNode string `json:"cluster_manager_node"` + Blocks struct { + Indices map[string]map[string]ClusterStateBlocksIndex `json:"indices"` + } `json:"blocks"` + Nodes map[string]ClusterStateNodes `json:"nodes"` + Metadata ClusterStateMetaData `json:"metadata"` + response *opensearch.Response + RoutingTable struct { + Indices map[string]struct { + Shards map[string][]ClusterStateRoutingIndex `json:"shards"` + } `json:"indices"` + } `json:"routing_table"` + RoutingNodes ClusterStateRoutingNodes `json:"routing_nodes"` + Snapshots struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"snapshots"` + SnapshotDeletions struct { + SnapshotDeletions []json.RawMessage `json:"snapshot_deletions"` + } `json:"snapshot_deletions"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` + Restore struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"restore"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterStateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterStateBlocksIndex is a sub type of ClusterStateResp +type ClusterStateBlocksIndex struct { + Description string `json:"description"` + Retryable bool `json:"retryable"` + Levels []string `json:"levels"` +} + +// ClusterStateNodes is a sub type of ClusterStateResp +type ClusterStateNodes struct { + Name string `json:"name"` + EphemeralID string `json:"ephemeral_id"` + TransportAddress string `json:"transport_address"` + Attributes map[string]string `json:"attributes"` +} + +// ClusterStateMetaData is a sub type if ClusterStateResp containing metadata of the cluster +type ClusterStateMetaData struct { + ClusterUUID string `json:"cluster_uuid"` + ClusterUUIDCommitted bool `json:"cluster_uuid_committed"` + ClusterCoordination struct { + Term int `json:"term"` + LastCommittedConfig []string `json:"last_committed_config"` + LastAcceptedConfig []string `json:"last_accepted_config"` + VotingConfigExclusions []struct { + NodeID string `json:"node_id"` + NodeName string `json:"node_name"` + } `json:"voting_config_exclusions"` + } `json:"cluster_coordination"` + Templates map[string]json.RawMessage `json:"templates"` + Indices map[string]ClusterStateMetaDataIndex `json:"indices"` + IndexGraveyard struct { + Tombstones []struct { + Index struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + } `json:"index"` + DeleteDateInMillis int `json:"delete_date_in_millis"` + } `json:"tombstones"` + } `json:"index-graveyard"` + Repositories map[string]struct { + Type string `json:"type"` + Settings map[string]string `json:"settings"` + Generation int `json:"generation"` + PendingGeneration int `json:"pending_generation"` + } `json:"repositories"` + ComponentTemplate struct { + ComponentTemplate map[string]json.RawMessage `json:"component_template"` + } `json:"component_template"` + IndexTemplate struct { + IndexTemplate map[string]json.RawMessage `json:"index_template"` + } `json:"index_template"` + StoredScripts map[string]struct { + Lang string `json:"lang"` + Source string `json:"source"` + } `json:"stored_scripts"` + Ingest struct { + Pipeline []struct { + ID string `json:"id"` + Config struct { + Description string `json:"description"` + Processors json.RawMessage `json:"processors"` + } `json:"config"` + } `json:"pipeline"` + } `json:"ingest"` + DataStream struct { + DataStream map[string]ClusterStateMetaDataStream `json:"data_stream"` + } `json:"data_stream"` +} + +// ClusterStateMetaDataIndex is a sub type of ClusterStateMetaData containing information about an index +type ClusterStateMetaDataIndex struct { + Version int `json:"version"` + MappingVersion int `json:"mapping_version"` + SettingsVersion int `json:"settings_version"` + AliasesVersion int `json:"aliases_version"` + RoutingNumShards int `json:"routing_num_shards"` + State string `json:"state"` + Settings json.RawMessage `json:"settings"` + Mappings json.RawMessage `json:"mappings"` + Aliases []string `json:"aliases"` + PrimaryTerms map[string]int `json:"primary_terms"` + InSyncAllocations map[string][]string `json:"in_sync_allocations"` + RolloverInfo map[string]struct { + MetConditions map[string]string `json:"met_conditions"` + Time int `json:"time"` + } `json:"rollover_info"` + System bool `json:"system"` +} + +// ClusterStateMetaDataStream is a sub type of ClusterStateMetaData containing information about a data stream +type ClusterStateMetaDataStream struct { + Name string `json:"name"` + TimestampField struct { + Name string `json:"name"` + } `json:"timestamp_field"` + Indices []struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + } `json:"indices"` + Generation int `json:"generation"` +} + +// ClusterStateRoutingIndex is a sub type of ClusterStateResp and ClusterStateRoutingNodes containing information about shard routing +type ClusterStateRoutingIndex struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node *string `json:"node"` + RelocatingNode *string `json:"relocating_node"` + Shard int `json:"shard"` + Index string `json:"index"` + ExpectedShardSizeInBytes int `json:"expected_shard_size_in_bytes"` + AllocationID *struct { + ID string `json:"id"` + } `json:"allocation_id,omitempty"` + RecoverySource *struct { + Type string `json:"type"` + } `json:"recovery_source,omitempty"` + UnassignedInfo *struct { + Reason string `json:"reason"` + At string `json:"at"` + Delayed bool `json:"delayed"` + AllocationStatus string `json:"allocation_status"` + Details string `json:"details"` + } `json:"unassigned_info,omitempty"` +} + +// ClusterStateRoutingNodes is a sub type of ClusterStateResp containing information about shard assigned to nodes +type ClusterStateRoutingNodes struct { + Unassigned []ClusterStateRoutingIndex `json:"unassigned"` + Nodes map[string][]ClusterStateRoutingIndex `json:"nodes"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats-params.go new file mode 100644 index 0000000000..ca5df51ab6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// ClusterStatsParams represents possible parameters for the ClusterStatsReq +type ClusterStatsParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats.go new file mode 100644 index 0000000000..c14c7c9d16 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-stats.go @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterStatsReq represents possible options for the /_cluster/stats request +type ClusterStatsReq struct { + NodeFilters []string + + Header http.Header + Params ClusterStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterStatsReq) GetRequest() (*http.Request, error) { + filters := strings.Join(r.NodeFilters, ",") + + var path strings.Builder + path.Grow(22 + len(filters)) + path.WriteString("/_cluster/stats") + if len(filters) > 0 { + path.WriteString("/nodes/") + path.WriteString(filters) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterStatsResp represents the returned struct of the ClusterStatsReq response +type ClusterStatsResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresCause `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Timestamp int64 `json:"timestamp"` + Status string `json:"status"` + Indices ClusterStatsIndices `json:"indices"` + Nodes ClusterStatsNodes `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterStatsIndices is a sub type of ClusterStatsResp containing cluster information about indices +type ClusterStatsIndices struct { + Count int `json:"count"` + Shards struct { + Total int `json:"total"` + Primaries int `json:"primaries"` + Replication float64 `json:"replication"` + Index struct { + Shards struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"shards"` + Primaries struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"primaries"` + Replication struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"replication"` + } `json:"index"` + } `json:"shards"` + Docs struct { + Count int64 `json:"count"` + Deleted int `json:"deleted"` + } `json:"docs"` + Store struct { + SizeInBytes int64 `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` + } `json:"store"` + Fielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + } `json:"fielddata"` + QueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` + } `json:"query_cache"` + Completion struct { + SizeInBytes int `json:"size_in_bytes"` + } `json:"completion"` + Segments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int64 `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int64 `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + Pressure struct { + TotalRejections int `json:"total_rejections"` + } `json:"pressure"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` + } `json:"segments"` + Mappings struct { + FieldTypes []struct { + Name string `json:"name"` + Count int `json:"count"` + IndexCount int `json:"index_count"` + } `json:"field_types"` + } `json:"mappings"` + Analysis struct { + CharFilterTypes []json.RawMessage `json:"char_filter_types"` + TokenizerTypes []json.RawMessage `json:"tokenizer_types"` + FilterTypes []json.RawMessage `json:"filter_types"` + AnalyzerTypes []json.RawMessage `json:"analyzer_types"` + BuiltInCharFilters []json.RawMessage `json:"built_in_char_filters"` + BuiltInTokenizers []json.RawMessage `json:"built_in_tokenizers"` + BuiltInFilters []json.RawMessage `json:"built_in_filters"` + BuiltInAnalyzers []json.RawMessage `json:"built_in_analyzers"` + } `json:"analysis"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` +} + +// ClusterStatsNodes is a sub type of ClusterStatsResp containing information about node stats +type ClusterStatsNodes struct { + Count struct { + Total int `json:"total"` + ClusterManager int `json:"cluster_manager"` + CoordinatingOnly int `json:"coordinating_only"` + Data int `json:"data"` + Ingest int `json:"ingest"` + Master int `json:"master"` + RemoteClusterClient int `json:"remote_cluster_client"` + Search int `json:"search"` + } `json:"count"` + Versions []string `json:"versions"` + Os struct { + AvailableProcessors int `json:"available_processors"` + AllocatedProcessors int `json:"allocated_processors"` + Names []struct { + Name string `json:"name"` + Count int `json:"count"` + } `json:"names"` + PrettyNames []struct { + PrettyName string `json:"pretty_name"` + Count int `json:"count"` + } `json:"pretty_names"` + Mem struct { + TotalInBytes int64 `json:"total_in_bytes"` + FreeInBytes int64 `json:"free_in_bytes"` + UsedInBytes int64 `json:"used_in_bytes"` + FreePercent int `json:"free_percent"` + UsedPercent int `json:"used_percent"` + } `json:"mem"` + } `json:"os"` + Process struct { + CPU struct { + Percent int `json:"percent"` + } `json:"cpu"` + OpenFileDescriptors struct { + Min int `json:"min"` + Max int `json:"max"` + Avg int `json:"avg"` + } `json:"open_file_descriptors"` + } `json:"process"` + Jvm struct { + MaxUptimeInMillis int64 `json:"max_uptime_in_millis"` + Versions []struct { + Version string `json:"version"` + VMName string `json:"vm_name"` + VMVersion string `json:"vm_version"` + VMVendor string `json:"vm_vendor"` + BundledJdk bool `json:"bundled_jdk"` + UsingBundledJdk bool `json:"using_bundled_jdk"` + Count int `json:"count"` + } `json:"versions"` + Mem struct { + HeapUsedInBytes int64 `json:"heap_used_in_bytes"` + HeapMaxInBytes int64 `json:"heap_max_in_bytes"` + } `json:"mem"` + Threads int `json:"threads"` + } `json:"jvm"` + Fs struct { + TotalInBytes int64 `json:"total_in_bytes"` + FreeInBytes int64 `json:"free_in_bytes"` + AvailableInBytes int64 `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"fs"` + Plugins []struct { + Name string `json:"name"` + Version string `json:"version"` + OpensearchVersion string `json:"opensearch_version"` + JavaVersion string `json:"java_version"` + Description string `json:"description"` + Classname string `json:"classname"` + CustomFoldername *string `json:"custom_foldername"` + ExtendedPlugins []string `json:"extended_plugins"` + OptionalExtendedPlugins []string `json:"optional_extended_plugins"` + HasNativeController bool `json:"has_native_controller"` + } `json:"plugins"` + NetworkTypes struct { + TransportTypes map[string]int `json:"transport_types"` + HTTPTypes map[string]int `json:"http_types"` + } `json:"network_types"` + DiscoveryTypes map[string]int `json:"discovery_types"` + PackagingTypes []struct { + Type string `json:"type"` + Count int `json:"count"` + } `json:"packaging_types"` + Ingest struct { + NumberOfPipelines int `json:"number_of_pipelines"` + ProcessorStats json.RawMessage `json:"processor_stats"` + } `json:"ingest"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions-params.go new file mode 100644 index 0000000000..66dd56cc24 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions-params.go @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterPostVotingConfigExclusionsParams represents possible parameters for the ClusterVotingConfigExclusionsReq +type ClusterPostVotingConfigExclusionsParams struct { + NodeIds string + NodeNames string + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterPostVotingConfigExclusionsParams) get() map[string]string { + params := make(map[string]string) + + if r.NodeIds != "" { + params["node_ids"] = r.NodeIds + } + + if r.NodeNames != "" { + params["node_names"] = r.NodeNames + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// ClusterDeleteVotingConfigExclusionsParams represents possible parameters for the ClusterVotingConfigExclusionsReq +type ClusterDeleteVotingConfigExclusionsParams struct { + WaitForRemoval *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ClusterDeleteVotingConfigExclusionsParams) get() map[string]string { + params := make(map[string]string) + + if r.WaitForRemoval != nil { + params["wait_for_removal"] = strconv.FormatBool(*r.WaitForRemoval) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions.go new file mode 100644 index 0000000000..cd736a9003 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster-voting_config_exclusions.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ClusterPostVotingConfigExclusionsReq represents possible options for the /_cluster/voting_config_exclusions request +type ClusterPostVotingConfigExclusionsReq struct { + Header http.Header + Params ClusterPostVotingConfigExclusionsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPostVotingConfigExclusionsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_cluster/voting_config_exclusions", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterDeleteVotingConfigExclusionsReq represents possible options for the /_cluster/voting_config_exclusions request +type ClusterDeleteVotingConfigExclusionsReq struct { + Header http.Header + Params ClusterDeleteVotingConfigExclusionsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterDeleteVotingConfigExclusionsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + "/_cluster/voting_config_exclusions", + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster.go new file mode 100644 index 0000000000..ae132d392a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_cluster.go @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type clusterClient struct { + apiClient *Client +} + +// AllocationExplain executes a /_cluster/allocation/explain request with the optional ClusterAllocationExplainReq +func (c clusterClient) AllocationExplain(ctx context.Context, req *ClusterAllocationExplainReq) (*ClusterAllocationExplainResp, error) { + if req == nil { + req = &ClusterAllocationExplainReq{} + } + + var ( + data ClusterAllocationExplainResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Health executes a /_cluster/health request with the optional ClusterHealthReq +func (c clusterClient) Health(ctx context.Context, req *ClusterHealthReq) (*ClusterHealthResp, error) { + if req == nil { + req = &ClusterHealthReq{} + } + + var ( + data ClusterHealthResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PendingTasks executes a /_cluster/pending_tasks request with the optional ClusterPendingTasksReq +func (c clusterClient) PendingTasks(ctx context.Context, req *ClusterPendingTasksReq) (*ClusterPendingTasksResp, error) { + if req == nil { + req = &ClusterPendingTasksReq{} + } + + var ( + data ClusterPendingTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// GetSettings executes a /_cluster/settings request with the optional ClusterGetSettingsReq +func (c clusterClient) GetSettings(ctx context.Context, req *ClusterGetSettingsReq) (*ClusterGetSettingsResp, error) { + if req == nil { + req = &ClusterGetSettingsReq{} + } + + var ( + data ClusterGetSettingsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PutSettings executes a /_cluster/settings request with the required ClusterPutSettingsReq +func (c clusterClient) PutSettings(ctx context.Context, req ClusterPutSettingsReq) (*ClusterPutSettingsResp, error) { + var ( + data ClusterPutSettingsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// State executes a /_cluster/state request with the optional ClusterStateReq +func (c clusterClient) State(ctx context.Context, req *ClusterStateReq) (*ClusterStateResp, error) { + if req == nil { + req = &ClusterStateReq{} + } + + var ( + data ClusterStateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a /_cluster/stats request with the optional ClusterStatsReq +func (c clusterClient) Stats(ctx context.Context, req *ClusterStatsReq) (*ClusterStatsResp, error) { + if req == nil { + req = &ClusterStatsReq{} + } + + var ( + data ClusterStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Reroute executes a /_cluster/reroute request with the required ClusterRerouteReq +func (c clusterClient) Reroute(ctx context.Context, req ClusterRerouteReq) (*ClusterRerouteResp, error) { + var ( + data ClusterRerouteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PostVotingConfigExclusions executes a /_cluster/voting_config_exclusions request with the optional ClusterPostVotingConfigExclusionsReq +func (c clusterClient) PostVotingConfigExclusions( + ctx context.Context, + req ClusterPostVotingConfigExclusionsReq, +) (*opensearch.Response, error) { + var ( + resp *opensearch.Response + err error + ) + if resp, err = c.apiClient.do(ctx, req, nil); err != nil { + return resp, err + } + + return resp, nil +} + +// DeleteVotingConfigExclusions executes a /_cluster/voting_config_exclusions request +// with the optional ClusterDeleteVotingConfigExclusionsReq +func (c clusterClient) DeleteVotingConfigExclusions( + ctx context.Context, + req ClusterDeleteVotingConfigExclusionsReq, +) (*opensearch.Response, error) { + var ( + resp *opensearch.Response + err error + ) + if resp, err = c.apiClient.do(ctx, req, nil); err != nil { + return resp, err + } + + return resp, nil +} + +// PutDecommission executes a /_cluster/decommission/awareness request with the optional ClusterPutDecommissionReq +func (c clusterClient) PutDecommission(ctx context.Context, req ClusterPutDecommissionReq) (*ClusterPutDecommissionResp, error) { + var ( + data ClusterPutDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteDecommission executes a /_cluster/decommission/awareness request with the optional ClusterDeleteDecommissionReq +func (c clusterClient) DeleteDecommission( + ctx context.Context, + req *ClusterDeleteDecommissionReq, +) (*ClusterDeleteDecommissionResp, error) { + if req == nil { + req = &ClusterDeleteDecommissionReq{} + } + + var ( + data ClusterDeleteDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// GetDecommission executes a /_cluster/decommission/awareness request with the optional ClusterGetDecommissionReq +func (c clusterClient) GetDecommission(ctx context.Context, req ClusterGetDecommissionReq) (*ClusterGetDecommissionResp, error) { + var ( + data ClusterGetDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Values); err != nil { + return &data, err + } + + return &data, nil +} + +// RemoteInfo executes a /_remote/info request with the optional ClusterRemoteInfoReq +func (c clusterClient) RemoteInfo(ctx context.Context, req *ClusterRemoteInfoReq) (*ClusterRemoteInfoResp, error) { + if req == nil { + req = &ClusterRemoteInfoReq{} + } + + var ( + data ClusterRemoteInfoResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Clusters); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create-params.go new file mode 100644 index 0000000000..2d6aa0d739 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ComponentTemplateCreateParams represents possible parameters for the ComponentTemplateCreateReq +type ComponentTemplateCreateParams struct { + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ComponentTemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create.go new file mode 100644 index 0000000000..237395778e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ComponentTemplateCreateReq represents possible options for the _component_template create request +type ComponentTemplateCreateReq struct { + ComponentTemplate string + + Body io.Reader + + Header http.Header + Params ComponentTemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateCreateResp represents the returned struct of the index create response +type ComponentTemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete-params.go new file mode 100644 index 0000000000..b63318c06a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// ComponentTemplateDeleteParams represents possible parameters for the ComponentTemplateDeleteReq +type ComponentTemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ComponentTemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete.go new file mode 100644 index 0000000000..ceb66bbb41 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ComponentTemplateDeleteReq represents possible options for the _component_template delete request +type ComponentTemplateDeleteReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + nil, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateDeleteResp represents the returned struct of the _component_template delete response +type ComponentTemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists-params.go new file mode 100644 index 0000000000..4e77792afb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ComponentTemplateExistsParams represents possible parameters for the ComponentTemplateExistsReq +type ComponentTemplateExistsParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ComponentTemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists.go new file mode 100644 index 0000000000..d70203e0dc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ComponentTemplateExistsReq represents possible options for the _component_template exists request +type ComponentTemplateExistsReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get-params.go new file mode 100644 index 0000000000..c9b207c093 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ComponentTemplateGetParams represents possible parameters for the ComponentTemplateGetReq +type ComponentTemplateGetParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ComponentTemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get.go new file mode 100644 index 0000000000..f9366bba91 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template-get.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ComponentTemplateGetReq represents possible options for the _component_template get request +type ComponentTemplateGetReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateGetReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_component_template/") + len(r.ComponentTemplate)) + path.WriteString("/_component_template") + if len(r.ComponentTemplate) > 0 { + path.WriteString("/") + path.WriteString(r.ComponentTemplate) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateGetResp represents the returned struct of the index create response +type ComponentTemplateGetResp struct { + ComponentTemplates []ComponentTemplateGetDetails `json:"component_templates"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ComponentTemplateGetDetails is a sub type of ComponentTemplateGetResp containing information about component template +type ComponentTemplateGetDetails struct { + Name string `json:"name"` + ComponentTemplate struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + } `json:"component_template"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template.go new file mode 100644 index 0000000000..6760af192c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_component_template.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type componentTemplateClient struct { + apiClient *Client +} + +// Create executes a creade componentTemplate request with the required ComponentTemplateCreateReq +func (c componentTemplateClient) Create(ctx context.Context, req ComponentTemplateCreateReq) (*ComponentTemplateCreateResp, error) { + var ( + data ComponentTemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete componentTemplate request with the required ComponentTemplateDeleteReq +func (c componentTemplateClient) Delete(ctx context.Context, req ComponentTemplateDeleteReq) (*ComponentTemplateDeleteResp, error) { + var ( + data ComponentTemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get componentTemplate request with the optional ComponentTemplateGetReq +func (c componentTemplateClient) Get(ctx context.Context, req *ComponentTemplateGetReq) (*ComponentTemplateGetResp, error) { + if req == nil { + req = &ComponentTemplateGetReq{} + } + + var ( + data ComponentTemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists componentTemplate request with the required ComponentTemplatExistsReq +func (c componentTemplateClient) Exists(ctx context.Context, req ComponentTemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete-params.go new file mode 100644 index 0000000000..d8413773fc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// DanglingDeleteParams represents possible parameters for the DanglingDeleteReq +type DanglingDeleteParams struct { + AcceptDataLoss *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DanglingDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.AcceptDataLoss != nil { + params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete.go new file mode 100644 index 0000000000..03ff832bf7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DanglingDeleteReq represents possible options for the delete dangling request +type DanglingDeleteReq struct { + IndexUUID string + + Header http.Header + Params DanglingDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_dangling/%s", r.IndexUUID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingDeleteResp represents the returned struct of the delete dangling response +type DanglingDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get-params.go new file mode 100644 index 0000000000..8a47236bbc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// DanglingGetParams represents possible parameters for the DanglingGetReq +type DanglingGetParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DanglingGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get.go new file mode 100644 index 0000000000..974d1f89bf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-get.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DanglingGetReq represents possible options for the dangling get request +type DanglingGetReq struct { + Header http.Header + Params DanglingGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_dangling", + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingGetResp represents the returned struct of the dangling get response +type DanglingGetResp struct { + Nodes struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []struct { + Type string `json:"type"` + Reason string `json:"reason"` + NodeID string `json:"node_id"` + CausedBy struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"caused_by"` + } `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + DanglingIndices []struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + CreationDateMillis int64 `json:"creation_date_millis"` + NodeIds []string `json:"node_ids"` + } `json:"dangling_indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import-params.go new file mode 100644 index 0000000000..cd5302d500 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// DanglingImportParams represents possible parameters for the DanglingImportReq +type DanglingImportParams struct { + AcceptDataLoss *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DanglingImportParams) get() map[string]string { + params := make(map[string]string) + + if r.AcceptDataLoss != nil { + params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import.go new file mode 100644 index 0000000000..83ad7ce6a6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling-import.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DanglingImportReq represents possible options for the dangling import request +type DanglingImportReq struct { + IndexUUID string + + Header http.Header + Params DanglingImportParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingImportReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_dangling/%s", r.IndexUUID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingImportResp represents the returned struct of thedangling import response +type DanglingImportResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingImportResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling.go new file mode 100644 index 0000000000..60922fde21 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_dangling.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type danglingClient struct { + apiClient *Client +} + +// Delete executes a delete dangling request with the required DanglingDeleteReq +func (c danglingClient) Delete(ctx context.Context, req DanglingDeleteReq) (*DanglingDeleteResp, error) { + var ( + data DanglingDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Import executes an import dangling request with the required DanglingImportReq +func (c danglingClient) Import(ctx context.Context, req DanglingImportReq) (*DanglingImportResp, error) { + var ( + data DanglingImportResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a /_dangling request with the optional DanglingGetReq +func (c danglingClient) Get(ctx context.Context, req *DanglingGetReq) (*DanglingGetResp, error) { + if req == nil { + req = &DanglingGetReq{} + } + + var ( + data DanglingGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create-params.go new file mode 100644 index 0000000000..00aa97ad66 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// DataStreamCreateParams represents possible parameters for the DataStreamCreateReq +type DataStreamCreateParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DataStreamCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create.go new file mode 100644 index 0000000000..148dee149a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-create.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DataStreamCreateReq represents possible options for the _data_stream create request +type DataStreamCreateReq struct { + DataStream string + + Header http.Header + Params DataStreamCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_data_stream/%s", r.DataStream), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamCreateResp represents the returned struct of the _data_stream create response +type DataStreamCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete-params.go new file mode 100644 index 0000000000..6aea4c00cc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// DataStreamDeleteParams represents possible parameters for the DataStreamDeleteReq +type DataStreamDeleteParams struct { + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DataStreamDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete.go new file mode 100644 index 0000000000..929b1f8cab --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DataStreamDeleteReq represents possible options for the index _data_stream delete request +type DataStreamDeleteReq struct { + DataStream string + + Header http.Header + Params DataStreamDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_data_stream/%s", r.DataStream), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamDeleteResp represents the returned struct of the _data_stream delete response +type DataStreamDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get-params.go new file mode 100644 index 0000000000..8f1aaffe9c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// DataStreamGetParams represents possible parameters for the DataStreamGetReq +type DataStreamGetParams struct { + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DataStreamGetParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get.go new file mode 100644 index 0000000000..20604aee6b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-get.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DataStreamGetReq represents possible options for the _data_stream get request +type DataStreamGetReq struct { + DataStreams []string + + Header http.Header + Params DataStreamGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamGetReq) GetRequest() (*http.Request, error) { + dataStreams := strings.Join(r.DataStreams, ",") + + var path strings.Builder + path.Grow(len("/_data_stream/") + len(dataStreams)) + path.WriteString("/_data_stream") + if len(r.DataStreams) > 0 { + path.WriteString("/") + path.WriteString(dataStreams) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamGetResp represents the returned struct of the _data_stream get response +type DataStreamGetResp struct { + DataStreams []DataStreamGetDetails `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DataStreamGetDetails is a sub type if DataStreamGetResp containing information about a data stream +type DataStreamGetDetails struct { + Name string `json:"name"` + TimestampField struct { + Name string `json:"name"` + } `json:"timestamp_field"` + Indices []DataStreamIndices `json:"indices"` + Generation int `json:"generation"` + Status string `json:"status"` + Template string `json:"template"` +} + +// DataStreamIndices is a sub type of DataStreamGetDetails containing information about an index +type DataStreamIndices struct { + Name string `json:"index_name"` + UUID string `json:"index_uuid"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats-params.go new file mode 100644 index 0000000000..fb43a0caa0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// DataStreamStatsParams represents possible parameters for the DataStreamCreateReq +type DataStreamStatsParams struct { + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DataStreamStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats.go new file mode 100644 index 0000000000..d99f8dc89c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream-stats.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DataStreamStatsReq represents possible options for the _data_stream stats request +type DataStreamStatsReq struct { + DataStreams []string + + Header http.Header + Params DataStreamStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamStatsReq) GetRequest() (*http.Request, error) { + dataStreams := strings.Join(r.DataStreams, ",") + + var path strings.Builder + path.Grow(len("/_data_stream//_stats") + len(dataStreams)) + path.WriteString("/_data_stream/") + if len(r.DataStreams) > 0 { + path.WriteString(dataStreams) + path.WriteString("/") + } + path.WriteString("_stats") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamStatsResp represents the returned struct of the _data_stream stats response +type DataStreamStatsResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []struct { + Shard int `json:"shard"` + Index string `json:"index"` + Status string `json:"status"` + Reason FailuresCause `json:"reason"` + } `json:"failures"` + } `json:"_shards"` + DataStreamCount int `json:"data_stream_count"` + BackingIndices int `json:"backing_indices"` + TotalStoreSizeBytes int64 `json:"total_store_size_bytes"` + DataStreams []DataStreamStatsDetails `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DataStreamStatsDetails is a sub type of DataStreamStatsResp containing information about a data stream +type DataStreamStatsDetails struct { + DataStream string `json:"data_stream"` + BackingIndices int `json:"backing_indices"` + StoreSizeBytes int64 `json:"store_size_bytes"` + MaximumTimestamp int64 `json:"maximum_timestamp"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream.go new file mode 100644 index 0000000000..2942d1d6b4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_datastream.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type dataStreamClient struct { + apiClient *Client +} + +// Create executes a creade dataStream request with the required DataStreamCreateReq +func (c dataStreamClient) Create(ctx context.Context, req DataStreamCreateReq) (*DataStreamCreateResp, error) { + var ( + data DataStreamCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete dataStream request with the required DataStreamDeleteReq +func (c dataStreamClient) Delete(ctx context.Context, req DataStreamDeleteReq) (*DataStreamDeleteResp, error) { + var ( + data DataStreamDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get dataStream request with the optional DataStreamGetReq +func (c dataStreamClient) Get(ctx context.Context, req *DataStreamGetReq) (*DataStreamGetResp, error) { + if req == nil { + req = &DataStreamGetReq{} + } + + var ( + data DataStreamGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a stats dataStream request with the optional DataStreamStatsReq +func (c dataStreamClient) Stats(ctx context.Context, req *DataStreamStatsReq) (*DataStreamStatsResp, error) { + if req == nil { + req = &DataStreamStatsReq{} + } + + var ( + data DataStreamStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create-params.go new file mode 100644 index 0000000000..a3370d8e95 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// DocumentCreateParams represents possible parameters for the DocumentCreateReq +type DocumentCreateParams struct { + Pipeline string + Refresh string + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create.go new file mode 100644 index 0000000000..10a7a4acba --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-create.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentCreateReq represents possible options for the //_create request +type DocumentCreateReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params DocumentCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentCreateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(10 + len(r.Index) + len(r.DocumentID)) + path.WriteString("/") + path.WriteString(r.Index) + path.WriteString("/_create/") + path.WriteString(r.DocumentID) + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentCreateResp represents the returned struct of the /_doc response +type DocumentCreateResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Type string `json:"_type"` // Deprecated field + ForcedRefresh bool `json:"forced_refresh"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete-params.go new file mode 100644 index 0000000000..c1db1031c2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete-params.go @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// DocumentDeleteParams represents possible parameters for the DocumentDeleteReq +type DocumentDeleteParams struct { + IfPrimaryTerm *int + IfSeqNo *int + Refresh string + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete.go new file mode 100644 index 0000000000..7a282f86f0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentDeleteReq represents possible options for the //_doc/ delete request +type DocumentDeleteReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(7 + len(r.Index) + len(r.DocumentID)) + path.WriteString("/") + path.WriteString(r.Index) + path.WriteString("/_doc/") + path.WriteString(r.DocumentID) + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteResp represents the returned struct of the //_doc/ response +type DocumentDeleteResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Type string `json:"_type"` // Deprecated field + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query-params.go new file mode 100644 index 0000000000..74c5a23f1c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query-params.go @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// DocumentDeleteByQueryParams represents possible parameters for the DocumentDeleteByQueryReq +type DocumentDeleteByQueryParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + Conflicts string + DefaultOperator string + Df string + ExpandWildcards string + From *int + IgnoreUnavailable *bool + Lenient *bool + MaxDocs *int + Preference string + Query string + Refresh *bool + RequestCache *bool + RequestsPerSecond *int + Routing []string + Scroll time.Duration + ScrollSize *int + SearchTimeout time.Duration + SearchType string + Size *int + Slices interface{} + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + TerminateAfter *int + Timeout time.Duration + Version *bool + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentDeleteByQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.Conflicts != "" { + params["conflicts"] = r.Conflicts + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollSize != nil { + params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) + } + + if r.SearchTimeout != 0 { + params["search_timeout"] = formatDuration(r.SearchTimeout) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query.go new file mode 100644 index 0000000000..e936006e7c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentDeleteByQueryReq represents possible options for the //_delete_by_query request +type DocumentDeleteByQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params DocumentDeleteByQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteByQueryReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_delete_by_query", strings.Join(r.Indices, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteByQueryResp represents the returned struct of the //_delete_by_query response +type DocumentDeleteByQueryResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float32 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` // Unknow struct, open an issue with an example response so we can add it + Task string `json:"task,omitempty"` // Needed when wait_for_completion is set to false + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteByQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle-params.go new file mode 100644 index 0000000000..13fb6bc2a3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentDeleteByQueryRethrottleParams represents possible parameters for the DocumentDeleteByQueryRethrottleReq +type DocumentDeleteByQueryRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentDeleteByQueryRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle.go new file mode 100644 index 0000000000..5f741ef645 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-delete_by_query_rethrottle.go @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentDeleteByQueryRethrottleReq represents possible options for the /_delete_by_query//_rethrottle request +type DocumentDeleteByQueryRethrottleReq struct { + TaskID string + + Header http.Header + Params DocumentDeleteByQueryRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteByQueryRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_delete_by_query/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteByQueryRethrottleResp represents the returned struct of the /_delete_by_query//_rethrottle response +type DocumentDeleteByQueryRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average DocumentDeleteByQueryRethrottleResourceInfo `json:"average"` + Max DocumentDeleteByQueryRethrottleResourceInfo `json:"max"` + Min DocumentDeleteByQueryRethrottleResourceInfo `json:"min"` + Total DocumentDeleteByQueryRethrottleResourceInfo `json:"total"` + ThreadInfo struct { + ActiveThreads int `json:"active_threads"` + ThreadExecutions int `json:"thread_executions"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + NodeFailures []FailuresCause `json:"node_failures"` + response *opensearch.Response +} + +// DocumentDeleteByQueryRethrottleResourceInfo is a sub type of DocumentDeleteByQueryRethrottleResp containing resource stats +type DocumentDeleteByQueryRethrottleResourceInfo struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteByQueryRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists-params.go new file mode 100644 index 0000000000..b6ce6b0910 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists-params.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExistsParams represents possible parameters for the DocumentExistsReq +type DocumentExistsParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists.go new file mode 100644 index 0000000000..01c7d2afe0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentExistsReq represents possible options for the document exists request +type DocumentExistsReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source-params.go new file mode 100644 index 0000000000..3424507651 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source-params.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExistsSourceParams represents possible parameters for the DocumentExistsSourceReq +type DocumentExistsSourceParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentExistsSourceParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source.go new file mode 100644 index 0000000000..35ee3001bf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-exists_source.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentExistsSourceReq represents possible options for the _source exists request +type DocumentExistsSourceReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentExistsSourceParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExistsSourceReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/%s/_source/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain-params.go new file mode 100644 index 0000000000..2578b4c611 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain-params.go @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExplainParams represents possible parameters for the DocumentExplainReq +type DocumentExplainParams struct { + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + Lenient *bool + Preference string + Query string + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentExplainParams) get() map[string]string { + params := make(map[string]string) + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain.go new file mode 100644 index 0000000000..2610fe0db7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-explain.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentExplainReq represents possible options for the //_explain/ request +type DocumentExplainReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params DocumentExplainParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExplainReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_explain/%s", r.Index, r.DocumentID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentExplainResp represents the returned struct of the //_explain/ response +type DocumentExplainResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Type string `json:"_type"` // Deprecated field + Matched bool `json:"matched"` + Explanation DocumentExplainDetails `json:"explanation"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentExplainResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DocumentExplainDetails is a sub type of DocumentExplainResp containing information about why a query does what it does +type DocumentExplainDetails struct { + Value float64 `json:"value"` + Description string `json:"description"` + Details []DocumentExplainDetails `json:"details"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get-params.go new file mode 100644 index 0000000000..5366a6b851 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get-params.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentGetParams represents possible parameters for the DocumentGetReq +type DocumentGetParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get.go new file mode 100644 index 0000000000..39862ad4c2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-get.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentGetReq represents possible options for the //_doc/ get request +type DocumentGetReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentGetResp represents the returned struct of the //_doc/ get response +type DocumentGetResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Found bool `json:"found"` + Type string `json:"_type"` // Deprecated field + Source json.RawMessage `json:"_source"` + Fields json.RawMessage `json:"fields"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source-params.go new file mode 100644 index 0000000000..ef1258c78f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source-params.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentSourceParams represents possible parameters for the DocumentSourceReq +type DocumentSourceParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + // Deprecated: This parameter is similar to SourceIncludes, please use that instead. + Source interface{} + SourceExcludes []string + SourceIncludes []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r DocumentSourceParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source.go new file mode 100644 index 0000000000..c2c9bb5daf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document-source.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// DocumentSourceReq represents possible options for the //_source/ get request +type DocumentSourceReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentSourceParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentSourceReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s/_source/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentSourceResp represents the returned struct of the //_source/ get response +type DocumentSourceResp struct { + Source json.RawMessage + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentSourceResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document.go new file mode 100644 index 0000000000..082119dc5a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_document.go @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type documentClient struct { + apiClient *Client +} + +// Create executes a creade document request with the required DocumentCreateReq +func (c documentClient) Create(ctx context.Context, req DocumentCreateReq) (*DocumentCreateResp, error) { + var ( + data DocumentCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete document request with the required DocumentDeleteReq +func (c documentClient) Delete(ctx context.Context, req DocumentDeleteReq) (*DocumentDeleteResp, error) { + var ( + data DocumentDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteByQuery executes a delete by query request with the required DocumentDeleteByQueryReq +func (c documentClient) DeleteByQuery(ctx context.Context, req DocumentDeleteByQueryReq) (*DocumentDeleteByQueryResp, error) { + var ( + data DocumentDeleteByQueryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteByQueryRethrottle executes a delete by query rethrottle request with the optional DocumentDeleteByQueryRethrottleReq +func (c documentClient) DeleteByQueryRethrottle( + ctx context.Context, + req DocumentDeleteByQueryRethrottleReq, +) (*DocumentDeleteByQueryRethrottleResp, error) { + var ( + data DocumentDeleteByQueryRethrottleResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists document request with the required DocumentExistsReq +func (c documentClient) Exists(ctx context.Context, req DocumentExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// ExistsSource executes a exists source request with the required DocumentExistsSourceReq +func (c documentClient) ExistsSource(ctx context.Context, req DocumentExistsSourceReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Explain executes an explain document request with the required DocumentExplainReq +func (c documentClient) Explain(ctx context.Context, req DocumentExplainReq) (*DocumentExplainResp, error) { + var ( + data DocumentExplainResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a //_doc/ request with the required DocumentGetReq +func (c documentClient) Get(ctx context.Context, req DocumentGetReq) (*DocumentGetResp, error) { + var ( + data DocumentGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Source executes a //_source/ request with the required DocumentSourceReq +func (c documentClient) Source(ctx context.Context, req DocumentSourceReq) (*DocumentSourceResp, error) { + var ( + data DocumentSourceResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Source); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index-params.go new file mode 100644 index 0000000000..39ad2032a2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index-params.go @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexParams represents possible parameters for the IndexReq +type IndexParams struct { + IfPrimaryTerm *int + IfSeqNo *int + OpType string + Pipeline string + Refresh string + RequireAlias *bool + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.OpType != "" { + params["op_type"] = r.OpType + } + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index.go new file mode 100644 index 0000000000..d772a758fe --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Index executes a /_doc request with the given IndexReq +func (c Client) Index(ctx context.Context, req IndexReq) (*IndexResp, error) { + var ( + data IndexResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// IndexReq represents possible options for the /_doc request +type IndexReq struct { + Index string + DocumentID string + Body io.Reader + Header http.Header + Params IndexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexReq) GetRequest() (*http.Request, error) { + var method, path string + + if r.DocumentID != "" { + method = "PUT" + path = fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID) + } else { + method = "POST" + path = fmt.Sprintf("/%s/_doc", r.Index) + } + + return opensearch.BuildRequest( + method, + path, + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexResp represents the returned struct of the /_doc response +type IndexResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Type string `json:"_type"` // Deprecated field + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create-params.go new file mode 100644 index 0000000000..0253cc7469 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexTemplateCreateParams represents possible parameters for the IndexTemplateCreateReq +type IndexTemplateCreateParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create.go new file mode 100644 index 0000000000..1d6e35bf08 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateCreateReq represents possible options for the index create request +type IndexTemplateCreateReq struct { + IndexTemplate string + + Body io.Reader + + Header http.Header + Params IndexTemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateCreateResp represents the returned struct of the index create response +type IndexTemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete-params.go new file mode 100644 index 0000000000..3a86b8e26c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// IndexTemplateDeleteParams represents possible parameters for the IndexTemplateDeleteReq +type IndexTemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete.go new file mode 100644 index 0000000000..0c10116860 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateDeleteReq represents possible options for the index create request +type IndexTemplateDeleteReq struct { + IndexTemplate string + + Header http.Header + Params IndexTemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateDeleteResp represents the returned struct of the index create response +type IndexTemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists-params.go new file mode 100644 index 0000000000..2d995950f7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexTemplateExistsParams represents possible parameters for the IndexTemplateExistsReq +type IndexTemplateExistsParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists.go new file mode 100644 index 0000000000..24d3c534a3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateExistsReq represents possible options for the index create request +type IndexTemplateExistsReq struct { + IndexTemplate string + + Header http.Header + Params IndexTemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get-params.go new file mode 100644 index 0000000000..39fae17662 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexTemplateGetParams represents possible parameters for the IndexTemplateGetReq +type IndexTemplateGetParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get.go new file mode 100644 index 0000000000..db2bb89b93 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-get.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateGetReq represents possible options for the index create request +type IndexTemplateGetReq struct { + IndexTemplates []string + + Header http.Header + Params IndexTemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_index_template/%s", strings.Join(r.IndexTemplates, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateGetResp represents the returned struct of the index create response +type IndexTemplateGetResp struct { + IndexTemplates []IndexTemplateGetDetails `json:"index_templates"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndexTemplateGetDetails is a sub type of IndexTemplateGetResp containing information about an index template +type IndexTemplateGetDetails struct { + Name string `json:"name"` + IndexTemplate struct { + IndexPatterns []string `json:"index_patterns"` + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + ComposedOf []string `json:"composed_of"` + Priority int `json:"priority"` + Version int `json:"version"` + DataStream json.RawMessage `json:"data_stream"` + } `json:"index_template"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate-params.go new file mode 100644 index 0000000000..7a5fa3030f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexTemplateSimulateParams represents possible parameters for the IndexTemplateSimulateReq +type IndexTemplateSimulateParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateSimulateParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate.go new file mode 100644 index 0000000000..5cc253a4e1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateSimulateReq represents possible options for the index create request +type IndexTemplateSimulateReq struct { + IndexTemplate string + + Body io.Reader + + Header http.Header + Params IndexTemplateSimulateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateSimulateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_index_template/_simulate/%s", r.IndexTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateSimulateResp represents the returned struct of the index create response +type IndexTemplateSimulateResp struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + Overlapping []struct { + Name string `json:"name"` + IndexPatterns []string `json:"index_patterns"` + } `json:"overlapping"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateSimulateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index-params.go new file mode 100644 index 0000000000..8395d24582 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndexTemplateSimulateIndexParams represents possible parameters for the IndexTemplateSimulateIndexReq +type IndexTemplateSimulateIndexParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndexTemplateSimulateIndexParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index.go new file mode 100644 index 0000000000..3d59105fe9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template-simulate_index.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndexTemplateSimulateIndexReq represents possible options for the index create request +type IndexTemplateSimulateIndexReq struct { + Index string + + Body io.Reader + + Header http.Header + Params IndexTemplateSimulateIndexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateSimulateIndexReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_index_template/_simulate_index/%s", r.Index), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateSimulateIndexResp represents the returned struct of the index create response +type IndexTemplateSimulateIndexResp struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + Overlapping []struct { + Name string `json:"name"` + IndexPatterns []string `json:"index_patterns"` + } `json:"overlapping"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateSimulateIndexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template.go new file mode 100644 index 0000000000..a42c553407 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_index_template.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type indexTemplateClient struct { + apiClient *Client +} + +// Create executes a creade indexTemplate request with the required IndexTemplateCreateReq +func (c indexTemplateClient) Create(ctx context.Context, req IndexTemplateCreateReq) (*IndexTemplateCreateResp, error) { + var ( + data IndexTemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete indexTemplate request with the required IndexTemplateDeleteReq +func (c indexTemplateClient) Delete(ctx context.Context, req IndexTemplateDeleteReq) (*IndexTemplateDeleteResp, error) { + var ( + data IndexTemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get indexTemplate request with the optional IndexTemplateGetReq +func (c indexTemplateClient) Get(ctx context.Context, req *IndexTemplateGetReq) (*IndexTemplateGetResp, error) { + if req == nil { + req = &IndexTemplateGetReq{} + } + + var ( + data IndexTemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists indexTemplate request with the required IndexTemplatExistsReq +func (c indexTemplateClient) Exists(ctx context.Context, req IndexTemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Simulate executes a _simulate indexTemplate request with the required IndexTemplateSimulateReq +func (c indexTemplateClient) Simulate(ctx context.Context, req IndexTemplateSimulateReq) (*IndexTemplateSimulateResp, error) { + var ( + data IndexTemplateSimulateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SimulateIndex executes a _simulate_index indexTemplate request with the required IndexTemplateSimulateIndexReq +func (c indexTemplateClient) SimulateIndex( + ctx context.Context, + req IndexTemplateSimulateIndexReq, +) (*IndexTemplateSimulateIndexResp, error) { + var ( + data IndexTemplateSimulateIndexResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias-params.go new file mode 100644 index 0000000000..33c96adb09 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias-params.go @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// AliasDeleteParams represents possible parameters for the AliasDeleteReq +type AliasDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r AliasDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// AliasGetParams represents possible parameters for the AliasGetReq +type AliasGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r AliasGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// AliasPutParams represents possible parameters for the AliasPutReq +type AliasPutParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r AliasPutParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// AliasExistsParams represents possible parameters for the AliasExistsReq +type AliasExistsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r AliasExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias.go new file mode 100644 index 0000000000..fbbafdc967 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-alias.go @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type aliasClient struct { + apiClient *Client +} + +// Delete executes a delete alias request with the required AliasDeleteReq +func (c aliasClient) Delete(ctx context.Context, req AliasDeleteReq) (*AliasDeleteResp, error) { + var ( + data AliasDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get alias request with the required AliasGetReq +func (c aliasClient) Get(ctx context.Context, req AliasGetReq) (*AliasGetResp, error) { + var ( + data AliasGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put alias request with the required AliasPutReq +func (c aliasClient) Put(ctx context.Context, req AliasPutReq) (*AliasPutResp, error) { + var ( + data AliasPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes an exists alias request with the required AliasExistsReq +func (c aliasClient) Exists(ctx context.Context, req AliasExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// AliasDeleteReq represents possible options for the alias delete request +type AliasDeleteReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasDeleteReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(aliases)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasDeleteResp represents the returned struct of the alias delete response +type AliasDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasGetReq represents possible options for the alias get request +type AliasGetReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasGetReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(aliases)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasGetResp represents the returned struct of the alias get response +type AliasGetResp struct { + Indices map[string]struct { + Aliases map[string]json.RawMessage `json:"aliases"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasPutReq represents possible options for the alias put request +type AliasPutReq struct { + Indices []string + Alias string + + Header http.Header + Params AliasPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Alias)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(r.Alias) + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasPutResp represents the returned struct of the alias put response +type AliasPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasExistsReq represents possible options for the alias exists request +type AliasExistsReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasExistsReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Alias)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "HEAD", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze-params.go new file mode 100644 index 0000000000..2d32a23ff3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// IndicesAnalyzeParams represents possible parameters for the IndicesAnalyzeReq +type IndicesAnalyzeParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesAnalyzeParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze.go new file mode 100644 index 0000000000..008fd96b7c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-analyze.go @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesAnalyzeReq represents possible options for the /_analyze request +type IndicesAnalyzeReq struct { + Index string + Body IndicesAnalyzeBody + + Header http.Header + Params IndicesAnalyzeParams +} + +// IndicesAnalyzeBody represents the request body for the indices analyze request +type IndicesAnalyzeBody struct { + Analyzer string `json:"analyzer,omitempty"` + Attributes []string `json:"attributes,omitempty"` + CharFilter []string `json:"char_filter,omitempty"` + Explain bool `json:"explain,omitempty"` + Field string `json:"field,omitempty"` + Filter []string `json:"filter,omitempty"` + Normalizer string `json:"normalizer,omitempty"` + Text []string `json:"text"` + Tokenizer string `json:"tokenizer,omitempty"` +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesAnalyzeReq) GetRequest() (*http.Request, error) { + body, err := json.Marshal(r.Body) + if err != nil { + return nil, err + } + + var path strings.Builder + path.Grow(10 + len(r.Index)) + if len(r.Index) != 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_analyze") + return opensearch.BuildRequest( + "GET", + path.String(), + bytes.NewReader(body), + r.Params.get(), + r.Header, + ) +} + +// IndicesAnalyzeResp represents the returned struct of the index create response +type IndicesAnalyzeResp struct { + Tokens []IndicesAnalyzeToken `json:"tokens"` + Detail struct { + CustomAnalyzer bool `json:"custom_analyzer"` + Charfilters []IndicesAnalyzeCharfilter `json:"charfilters"` + Tokenizer IndicesAnalyzeTokenizer `json:"tokenizer"` + Tokenfilters []IndicesAnalyzeTokenfilters `json:"tokenfilters"` + Analyzer IndicesAnalyzeInfo `json:"analyzer"` + } `json:"detail"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesAnalyzeResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesAnalyzeToken is a sut type of IndicesAnalyzeResp containing information about analyzer token +type IndicesAnalyzeToken struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` +} + +// IndicesAnalyzeTokenizer is a sub type of IndicesAnalyzerResp containing information about the tokenizer name and tokens +type IndicesAnalyzeTokenizer struct { + Name string `json:"name"` + Tokens []IndicesAnalyzeToken `json:"tokens"` +} + +// IndicesAnalyzeTokenfilters is a sub type of IndicesAnalyzerResp containing information about the token filers name and tokens +type IndicesAnalyzeTokenfilters struct { + Name string `json:"name"` + Tokens []struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` + Keyword bool `json:"keyword"` + } `json:"tokens"` +} + +// IndicesAnalyzeCharfilter is a sub type of IndicesAnalyzerResp containing information about the char filter name and filtered text +type IndicesAnalyzeCharfilter struct { + Name string `json:"name"` + FilteredText []string `json:"filtered_text"` +} + +// IndicesAnalyzeInfo is a sub type of IndicesAnalyzerResp containing information about the analyzer name and tokens +type IndicesAnalyzeInfo struct { + Name string `json:"name"` + Tokens []struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` + Bytes string `json:"bytes"` + PositionLength int `json:"positionLength"` + TermFrequency int `json:"termFrequency"` + } `json:"tokens"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block-params.go new file mode 100644 index 0000000000..f951b8367b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block-params.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesBlockParams represents possible parameters for the IndicesBlockReq +type IndicesBlockParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesBlockParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block.go new file mode 100644 index 0000000000..0d54cea7bf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-block.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesBlockReq represents possible options for the index create request +type IndicesBlockReq struct { + Indices []string + Block string + + Header http.Header + Params IndicesBlockParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesBlockReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Block)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_block/") + path.WriteString(r.Block) + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesBlockResp represents the returned struct of the index create response +type IndicesBlockResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Indices []struct { + Name string `json:"name"` + Blocked bool `json:"blocked"` + FailedShards []struct { + ID int `json:"id"` + Failures []FailuresShard `json:"failures"` + } `json:"failed_shards"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesBlockResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache-params.go new file mode 100644 index 0000000000..f054bad672 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache-params.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesClearCacheParams represents possible parameters for the IndicesClearCacheReq +type IndicesClearCacheParams struct { + AllowNoIndices *bool + ExpandWildcards string + Fielddata *bool + Fields []string + IgnoreUnavailable *bool + Query *bool + Request *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesClearCacheParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Fielddata != nil { + params["fielddata"] = strconv.FormatBool(*r.Fielddata) + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Query != nil { + params["query"] = strconv.FormatBool(*r.Query) + } + + if r.Request != nil { + params["request"] = strconv.FormatBool(*r.Request) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache.go new file mode 100644 index 0000000000..f29fa682b6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-cache.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesClearCacheReq represents possible options for the index clear cache request +type IndicesClearCacheReq struct { + Indices []string + + Header http.Header + Params IndicesClearCacheParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesClearCacheReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_cache/clear") + len(indices)) + if len(indices) != 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_cache/clear") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesClearCacheResp represents the returned struct of the index clear cache response +type IndicesClearCacheResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesClearCacheResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone-params.go new file mode 100644 index 0000000000..d9d9fe377f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// IndicesCloneParams represents possible parameters for the IndicesCloneReq +type IndicesCloneParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesCloneParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone.go new file mode 100644 index 0000000000..adaddb9f09 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-clone.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesCloneReq represents possible options for the index clone request +type IndicesCloneReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesCloneParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCloneReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_clone/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCloneResp represents the returned struct of the index clone response +type IndicesCloneResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCloneResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close-params.go new file mode 100644 index 0000000000..cf4ce42684 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesCloseParams represents possible parameters for the IndicesCloseReq +type IndicesCloseParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesCloseParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close.go new file mode 100644 index 0000000000..4275278aea --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-close.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesCloseReq represents possible options for the index close request +type IndicesCloseReq struct { + Index string + + Header http.Header + Params IndicesCloseParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCloseReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_close", r.Index), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesCloseResp represents the returned struct of the index close response +type IndicesCloseResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Indices map[string]struct { + Closed bool `json:"closed"` + FailedShards map[string]struct { + Failures []FailuresShard `json:"failures"` + } `json:"failed_shards"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCloseResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count-params.go new file mode 100644 index 0000000000..22945c61a4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count-params.go @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesCountParams represents possible parameters for the IndicesCountReq +type IndicesCountParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + ExpandWildcards string + IgnoreThrottled *bool + IgnoreUnavailable *bool + Lenient *bool + MinScore *int + Preference string + Query string + Routing []string + TerminateAfter *int + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesCountParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MinScore != nil { + params["min_score"] = strconv.FormatInt(int64(*r.MinScore), 10) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count.go new file mode 100644 index 0000000000..f8dc45395c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-count.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesCountReq represents possible options for the index shrink request +type IndicesCountReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesCountParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCountReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(8 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_count") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCountResp represents the returned struct of the index shrink response +type IndicesCountResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + } `json:"_shards"` + Count int `json:"count"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCountResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create-params.go new file mode 100644 index 0000000000..52abd6af67 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create-params.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// IndicesCreateParams represents possible parameters for the IndicesCreateReq +type IndicesCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create.go new file mode 100644 index 0000000000..cfd773d4c2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesCreateReq represents possible options for the index create request +type IndicesCreateReq struct { + Index string + Body io.Reader + Header http.Header + Params IndicesCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("%s%s", "/", r.Index), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCreateResp represents the returned struct of the index create response +type IndicesCreateResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete-params.go new file mode 100644 index 0000000000..a63fdfd5c8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesDeleteParams represents possible parameters for the IndicesDeleteReq +type IndicesDeleteParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesDeleteParams) get() map[string]string { + params := make(map[string]string) + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete.go new file mode 100644 index 0000000000..57857d3fc6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesDeleteReq represents possible options for the delete indices request +type IndicesDeleteReq struct { + Indices []string + Header http.Header + Params IndicesDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("%s%s", "/", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesDeleteResp represents the returned struct of the delete indices response +type IndicesDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists-params.go new file mode 100644 index 0000000000..424d5f41a5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesExistsParams represents possible parameters for the IndicesExistsReq +type IndicesExistsParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists.go new file mode 100644 index 0000000000..3d86e58400 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesExistsReq represents possible options for the index exists request +type IndicesExistsReq struct { + Indices []string + Header http.Header + Params IndicesExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("%s%s", "/", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps-params.go new file mode 100644 index 0000000000..46bd291c77 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps-params.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesFieldCapsParams represents possible parameters for the IndicesFieldCapsReq +type IndicesFieldCapsParams struct { + AllowNoIndices *bool + ExpandWildcards string + Fields []string + IgnoreUnavailable *bool + IncludeUnmapped *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesFieldCapsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeUnmapped != nil { + params["include_unmapped"] = strconv.FormatBool(*r.IncludeUnmapped) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps.go new file mode 100644 index 0000000000..3f4e29a772 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-field_caps.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesFieldCapsReq represents possible options for the index shrink request +type IndicesFieldCapsReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesFieldCapsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesFieldCapsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_field_caps") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesFieldCapsResp represents the returned struct of the index shrink response +type IndicesFieldCapsResp struct { + Indices []string `json:"indices"` + Fields map[string]map[string]struct { + Type string `json:"type"` + Searchable bool `json:"searchable"` + Aggregatable bool `json:"aggregatable"` + Indices []string `json:"indices"` + } `json:"fields"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesFieldCapsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush-params.go new file mode 100644 index 0000000000..ab660d50ae --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush-params.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesFlushParams represents possible parameters for the IndicesFlushReq +type IndicesFlushParams struct { + AllowNoIndices *bool + ExpandWildcards string + Force *bool + IgnoreUnavailable *bool + WaitIfOngoing *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesFlushParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Force != nil { + params["force"] = strconv.FormatBool(*r.Force) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.WaitIfOngoing != nil { + params["wait_if_ongoing"] = strconv.FormatBool(*r.WaitIfOngoing) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush.go new file mode 100644 index 0000000000..cf3bedff33 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-flush.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesFlushReq represents possible options for the flush indices request +type IndicesFlushReq struct { + Indices []string + + Header http.Header + Params IndicesFlushParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesFlushReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_flush") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_flush") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesFlushResp represents the returned struct of the flush indices response +type IndicesFlushResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesFlushResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge-params.go new file mode 100644 index 0000000000..9870bf8045 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesForcemergeParams represents possible parameters for the IndicesForcemergeReq +type IndicesForcemergeParams struct { + AllowNoIndices *bool + ExpandWildcards string + Flush *bool + IgnoreUnavailable *bool + MaxNumSegments *int + OnlyExpungeDeletes *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesForcemergeParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Flush != nil { + params["flush"] = strconv.FormatBool(*r.Flush) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MaxNumSegments != nil { + params["max_num_segments"] = strconv.FormatInt(int64(*r.MaxNumSegments), 10) + } + + if r.OnlyExpungeDeletes != nil { + params["only_expunge_deletes"] = strconv.FormatBool(*r.OnlyExpungeDeletes) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge.go new file mode 100644 index 0000000000..c8f3678072 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-forcemerge.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesForcemergeReq represents possible options for the /_forcemerge request +type IndicesForcemergeReq struct { + Indices []string + + Header http.Header + Params IndicesForcemergeParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesForcemergeReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_forcemerge") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_forcemerge") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesForcemergeResp represents the returned struct of the flush indices response +type IndicesForcemergeResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesForcemergeResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get-params.go new file mode 100644 index 0000000000..7be10ee1d7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get-params.go @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesGetParams represents possible parameters for the IndicesGetReq +type IndicesGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get.go new file mode 100644 index 0000000000..70f3b2ebae --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-get.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesGetReq represents possible options for the get indices request +type IndicesGetReq struct { + Indices []string + + Header http.Header + Params IndicesGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesGetResp represents the returned struct of the get indices response +type IndicesGetResp struct { + Indices map[string]struct { + DataStream *string `json:"data_stream,omitempty"` + Aliases map[string]struct{} `json:"aliases"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping-params.go new file mode 100644 index 0000000000..1aaa66b6dc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping-params.go @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// MappingGetParams represents possible parameters for the MappingGetReq +type MappingGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MappingGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// MappingPutParams represents possible parameters for the MappingPutReq +type MappingPutParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WriteIndexOnly *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MappingPutParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WriteIndexOnly != nil { + params["write_index_only"] = strconv.FormatBool(*r.WriteIndexOnly) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping.go new file mode 100644 index 0000000000..4b10f8aabb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-mapping.go @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type mappingClient struct { + apiClient *Client +} + +// Get executes a get mapping request with the required MappingGetReq +func (c mappingClient) Get(ctx context.Context, req *MappingGetReq) (*MappingGetResp, error) { + if req == nil { + req = &MappingGetReq{} + } + + var ( + data MappingGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put mapping request with the required MappingPutReq +func (c mappingClient) Put(ctx context.Context, req MappingPutReq) (*MappingPutResp, error) { + var ( + data MappingPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Field executes a field mapping request with the optional MappingFieldReq +func (c mappingClient) Field(ctx context.Context, req *MappingFieldReq) (*MappingFieldResp, error) { + if req == nil { + req = &MappingFieldReq{} + } + + var ( + data MappingFieldResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// MappingGetReq represents possible options for the mapping get request +type MappingGetReq struct { + Indices []string + + Header http.Header + Params MappingGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingGetReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_mapping") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// MappingGetResp represents the returned struct of the mapping get response +type MappingGetResp struct { + Indices map[string]struct { + Mappings json.RawMessage `json:"mappings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// MappingPutReq represents possible options for the mapping put request +type MappingPutReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MappingPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_mapping") + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MappingPutResp represents the returned struct of the mapping put response +type MappingPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// MappingFieldReq represents possible options for the mapping field request +type MappingFieldReq struct { + Indices []string + Fields []string + + Header http.Header + Params MappingPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingFieldReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + fields := strings.Join(r.Fields, ",") + + var path strings.Builder + path.Grow(17 + len(indices) + len(fields)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_mapping/field/") + path.WriteString(fields) + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// MappingFieldResp represents the returned struct of the mapping field response +type MappingFieldResp struct { + Indices map[string]struct { + Mappings json.RawMessage `json:"mappings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingFieldResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open-params.go new file mode 100644 index 0000000000..9e43944fda --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesOpenParams represents possible parameters for the IndicesOpenReq +type IndicesOpenParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesOpenParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open.go new file mode 100644 index 0000000000..28a3c81ce1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-open.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesOpenReq represents possible options for the index open request +type IndicesOpenReq struct { + Index string + + Header http.Header + Params IndicesOpenParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesOpenReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_open", r.Index), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesOpenResp represents the returned struct of the index open response +type IndicesOpenResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesOpenResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery-params.go new file mode 100644 index 0000000000..83426b1cd5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesRecoveryParams represents possible parameters for the IndicesShrinkReq +type IndicesRecoveryParams struct { + ActiveOnly *bool + Detailed *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesRecoveryParams) get() map[string]string { + params := make(map[string]string) + + if r.ActiveOnly != nil { + params["active_only"] = strconv.FormatBool(*r.ActiveOnly) + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery.go new file mode 100644 index 0000000000..68dfdcbc93 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-recovery.go @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesRecoveryReq represents possible options for the index shrink request +type IndicesRecoveryReq struct { + Indices []string + + Header http.Header + Params IndicesRecoveryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRecoveryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(11 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_recovery") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesRecoveryResp represents the returned struct of the index shrink response +type IndicesRecoveryResp struct { + Indices map[string]struct { + Shards []struct { + ID int `json:"id"` + Type string `json:"type"` + Stage string `json:"stage"` + Primary bool `json:"primary"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + StopTimeInMillis int64 `json:"stop_time_in_millis"` + TotalTimeInMillis int `json:"total_time_in_millis"` + Source IndicesRecoveryNodeInfo `json:"source"` + Target IndicesRecoveryNodeInfo `json:"target"` + Index struct { + Size struct { + TotalInBytes int `json:"total_in_bytes"` + ReusedInBytes int `json:"reused_in_bytes"` + RecoveredInBytes int `json:"recovered_in_bytes"` + Percent string `json:"percent"` + } `json:"size"` + Files struct { + Total int `json:"total"` + Reused int `json:"reused"` + Recovered int `json:"recovered"` + Percent string `json:"percent"` + } `json:"files"` + TotalTimeInMillis int `json:"total_time_in_millis"` + SourceThrottleTimeInMillis int `json:"source_throttle_time_in_millis"` + TargetThrottleTimeInMillis int `json:"target_throttle_time_in_millis"` + } `json:"index"` + Translog struct { + Recovered int `json:"recovered"` + Total int `json:"total"` + Percent string `json:"percent"` + TotalOnStart int `json:"total_on_start"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"translog"` + VerifyIndex struct { + CheckIndexTimeInMillis int `json:"check_index_time_in_millis"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"verify_index"` + } `json:"shards"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRecoveryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesRecoveryNodeInfo is a sub type of IndicesRecoveryResp represeing Node information +type IndicesRecoveryNodeInfo struct { + ID string `json:"id"` + Host string `json:"host"` + TransportAddress string `json:"transport_address"` + IP string `json:"ip"` + Name string `json:"name"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh-params.go new file mode 100644 index 0000000000..3b72da93bc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesRefreshParams represents possible parameters for the IndicesRefreshReq +type IndicesRefreshParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesRefreshParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh.go new file mode 100644 index 0000000000..d499175fe7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-refresh.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesRefreshReq represents possible options for the /_refresh request +type IndicesRefreshReq struct { + Indices []string + + Header http.Header + Params IndicesRefreshParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRefreshReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_refresh") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_refresh") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesRefreshResp represents the returned struct of the index shrink response +type IndicesRefreshResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRefreshResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve-params.go new file mode 100644 index 0000000000..4e4b46e659 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve-params.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// IndicesResolveParams represents possible parameters for the IndicesResolveReq +type IndicesResolveParams struct { + ExpandWildcards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesResolveParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve.go new file mode 100644 index 0000000000..882c6efb45 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-resolve.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesResolveReq represents possible options for the get indices request +type IndicesResolveReq struct { + Indices []string + + Header http.Header + Params IndicesResolveParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesResolveReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_resolve/index/%s", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesResolveResp represents the returned struct of the get indices response +type IndicesResolveResp struct { + Indices []struct { + Name string `json:"name"` + Attributes []string `json:"attributes"` + Aliases []string `json:"aliases"` + } `json:"indices"` + Aliases []struct { + Name string `json:"name"` + Indices []string `json:"indices"` + } `json:"aliases"` + DataStreams []struct { + Name string `json:"name"` + BackingIndices []string `json:"backing_indices"` + TimestampField string `json:"timestamp_field"` + } `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesResolveResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover-params.go new file mode 100644 index 0000000000..10476f0d67 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover-params.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesRolloverParams represents possible parameters for the IndicesRolloverReq +type IndicesRolloverParams struct { + DryRun *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesRolloverParams) get() map[string]string { + params := make(map[string]string) + + if r.DryRun != nil { + params["dry_run"] = strconv.FormatBool(*r.DryRun) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover.go new file mode 100644 index 0000000000..49bd020123 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-rollover.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesRolloverReq represents possible options for the index shrink request +type IndicesRolloverReq struct { + Alias string + Index string + + Body io.Reader + + Header http.Header + Params IndicesRolloverParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRolloverReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(12 + len(r.Alias) + len(r.Index)) + path.WriteString("/") + path.WriteString(r.Alias) + path.WriteString("/_rollover") + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesRolloverResp represents the returned struct of the index shrink response +type IndicesRolloverResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + OldIndex string `json:"old_index"` + NewIndex string `json:"new_index"` + RolledOver bool `json:"rolled_over"` + DryRun bool `json:"dry_run"` + Conditions map[string]bool `json:"conditions"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRolloverResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments-params.go new file mode 100644 index 0000000000..dda0a7222b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesSegmentsParams represents possible parameters for the IndicesSegmentsReq +type IndicesSegmentsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesSegmentsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments.go new file mode 100644 index 0000000000..4a4cc62563 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-segments.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesSegmentsReq represents possible options for the index shrink request +type IndicesSegmentsReq struct { + Indices []string + + Header http.Header + Params IndicesSegmentsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesSegmentsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(11 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_segments") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesSegmentsResp represents the returned struct of the index shrink response +type IndicesSegmentsResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` + } `json:"_shards"` + Indices map[string]struct { + Shards map[string][]IndicesSegmentsShards `json:"shards"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesSegmentsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesSegmentsShards is a sub type of IndicesSegmentsResp containing information about a shard +type IndicesSegmentsShards struct { + Routing struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node string `json:"node"` + } `json:"routing"` + NumCommittedSegments int `json:"num_committed_segments"` + NumSearchSegments int `json:"num_search_segments"` + Segments map[string]IndicesSegmentsDetails `json:"segments"` +} + +// IndicesSegmentsDetails is a sub type of IndicesSegmentsShards containing information about a segment +type IndicesSegmentsDetails struct { + Generation int `json:"generation"` + NumDocs int `json:"num_docs"` + DeletedDocs int `json:"deleted_docs"` + SizeInBytes int64 `json:"size_in_bytes"` + MemoryInBytes int `json:"memory_in_bytes"` + Committed bool `json:"committed"` + Search bool `json:"search"` + Version string `json:"version"` + Compound bool `json:"compound"` + MergeID string `json:"merge_id"` + Sort []struct { + Field string `json:"field"` + Mode string `json:"mode"` + Missing string `json:"missing"` + Reverse bool `json:"reverse"` + } `json:"sort"` + Attributes map[string]string `json:"attributes"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings-params.go new file mode 100644 index 0000000000..f22fc67bd2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings-params.go @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SettingsGetParams represents possible parameters for the SettingsGetReq +type SettingsGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SettingsGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} + +// SettingsPutParams represents possible parameters for the SettingsPutReq +type SettingsPutParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + PreserveExisting *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SettingsPutParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.PreserveExisting != nil { + params["preserve_existing"] = strconv.FormatBool(*r.PreserveExisting) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings.go new file mode 100644 index 0000000000..27b507fba0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-settings.go @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type settingsClient struct { + apiClient *Client +} + +// Get executes a get settings request with the required SettingsGetReq +func (c settingsClient) Get(ctx context.Context, req *SettingsGetReq) (*SettingsGetResp, error) { + if req == nil { + req = &SettingsGetReq{} + } + var ( + data SettingsGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put settings request with the required SettingsPutReq +func (c settingsClient) Put(ctx context.Context, req SettingsPutReq) (*SettingsPutResp, error) { + var ( + data SettingsPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SettingsGetReq represents possible options for the settings get request +type SettingsGetReq struct { + Indices []string + Settings []string + + Header http.Header + Params SettingsGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SettingsGetReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + settings := strings.Join(r.Settings, ",") + + var path strings.Builder + path.Grow(11 + len(indices) + len(settings)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_settings") + if len(settings) > 0 { + path.WriteString("/") + path.WriteString(settings) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SettingsGetResp represents the returned struct of the settings get response +type SettingsGetResp struct { + Indices map[string]struct { + Settings json.RawMessage `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SettingsGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SettingsPutReq represents possible options for the settings put request +type SettingsPutReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params SettingsPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SettingsPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_settings") + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SettingsPutResp represents the returned struct of the settings put response +type SettingsPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SettingsPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores-params.go new file mode 100644 index 0000000000..b9c4c7c1df --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesShardStoresParams represents possible parameters for the IndicesShardStoresReq +type IndicesShardStoresParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Status []string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesShardStoresParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if len(r.Status) > 0 { + params["status"] = strings.Join(r.Status, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores.go new file mode 100644 index 0000000000..91a7bd3f2a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shardstores.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesShardStoresReq represents possible options for the index shrink request +type IndicesShardStoresReq struct { + Indices []string + + Header http.Header + Params IndicesShardStoresParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesShardStoresReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(15 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_shard_stores") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesShardStoresResp represents the returned struct of the index shrink response +type IndicesShardStoresResp struct { + Indices map[string]struct { + Shards map[string]struct { + Stores []json.RawMessage `json:"stores"` + } `json:"shards"` + } `json:"indices"` + Failures []FailuresShard `json:"failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesShardStoresResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink-params.go new file mode 100644 index 0000000000..08579b5b57 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink-params.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesShrinkParams represents possible parameters for the IndicesShrinkReq +type IndicesShrinkParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesShrinkParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink.go new file mode 100644 index 0000000000..367bbd82e5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-shrink.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesShrinkReq represents possible options for the index shrink request +type IndicesShrinkReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesShrinkParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesShrinkReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_shrink/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesShrinkResp represents the returned struct of the index shrink response +type IndicesShrinkResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesShrinkResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split-params.go new file mode 100644 index 0000000000..b0a8bd0084 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split-params.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesSplitParams represents possible parameters for the IndicesSplitReq +type IndicesSplitParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesSplitParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split.go new file mode 100644 index 0000000000..dba82ff8e5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-split.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesSplitReq represents possible options for the index split request +type IndicesSplitReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesSplitParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesSplitReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_split/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesSplitResp represents the returned struct of the index split response +type IndicesSplitResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesSplitResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats-params.go new file mode 100644 index 0000000000..a883622f24 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats-params.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IndicesStatsParams represents possible parameters for the IndicesStatsReq +type IndicesStatsParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats.go new file mode 100644 index 0000000000..cd7f8c2b5e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-stats.go @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesStatsReq represents possible options for the index shrink request +type IndicesStatsReq struct { + Indices []string + Metrics []string + + Header http.Header + Params IndicesStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesStatsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(metrics)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_stats") + if len(metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesStatsResp represents the returned struct of the index shrink response +type IndicesStatsResp struct { + Shards IndicesStatsShards `json:"_shards"` + All IndicesStatsAll `json:"_all"` + Indices IndicesStatsIndices `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesStatsShards is a sub type of IndicesStatsResp containing information about how many shards got requested +type IndicesStatsShards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` +} + +// IndicesStatsDocs is a sub type of IndicesStatsInfo containing stats about the index documents +type IndicesStatsDocs struct { + Count int `json:"count"` + Deleted int `json:"deleted"` +} + +// IndicesStatsStore is a sub type of IndicesStatsInfo containing stats about index storage +type IndicesStatsStore struct { + SizeInBytes int64 `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` +} + +// IndicesStatsIndexing is a sub type of IndicesStatsInfo containing stats about document indexing +type IndicesStatsIndexing struct { + IndexTotal int `json:"index_total"` + IndexTimeInMillis int `json:"index_time_in_millis"` + IndexCurrent int `json:"index_current"` + IndexFailed int `json:"index_failed"` + DeleteTotal int `json:"delete_total"` + DeleteTimeInMillis int `json:"delete_time_in_millis"` + DeleteCurrent int `json:"delete_current"` + NoopUpdateTotal int `json:"noop_update_total"` + IsThrottled bool `json:"is_throttled"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + DocStatus map[string]int `json:"doc_status"` +} + +// IndicesStatsGet is a sub type of IndicesStatsInfo containing stats about index get +type IndicesStatsGet struct { + Total int `json:"total"` + TimeInMillis int `json:"time_in_millis"` + ExistsTotal int `json:"exists_total"` + ExistsTimeInMillis int `json:"exists_time_in_millis"` + MissingTotal int `json:"missing_total"` + MissingTimeInMillis int `json:"missing_time_in_millis"` + Current int `json:"current"` + GetTime string `json:"getTime"` +} + +// IndicesStatsSearch is a sub type of IndicesStatsInfo containing stats about index search +type IndicesStatsSearch struct { + OpenContexts int `json:"open_contexts"` + QueryTotal int `json:"query_total"` + QueryTimeInMillis int `json:"query_time_in_millis"` + QueryCurrent int `json:"query_current"` + ConcurrentQueryTotal int `json:"concurrent_query_total"` + ConcurrentQueryTimeInMillis int `json:"concurrent_query_time_in_millis"` + ConcurrentQueryCurrent int `json:"concurrent_query_current"` + ConcurrentAVGSliceCount float32 `json:"concurrent_avg_slice_count"` + FetchTotal int `json:"fetch_total"` + FetchTimeInMillis int `json:"fetch_time_in_millis"` + FetchCurrent int `json:"fetch_current"` + ScrollTotal int `json:"scroll_total"` + ScrollTimeInMillis int `json:"scroll_time_in_millis"` + ScrollCurrent int `json:"scroll_current"` + PointInTimeTotal int `json:"point_in_time_total"` + PointInTimeTimeInMillis int `json:"point_in_time_time_in_millis"` + PointInTimeCurrent int `json:"point_in_time_current"` + SuggestTotal int `json:"suggest_total"` + SuggestTimeInMillis int `json:"suggest_time_in_millis"` + SuggestCurrent int `json:"suggest_current"` + IdleReactivateCountTotal int `json:"search_idle_reactivate_count_total"` +} + +// IndicesStatsMerges is a sub type of IndicesStatsInfo containing stats about index merges +type IndicesStatsMerges struct { + Current int `json:"current"` + CurrentDocs int `json:"current_docs"` + CurrentSizeInBytes int `json:"current_size_in_bytes"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + TotalDocs int `json:"total_docs"` + TotalSizeInBytes int64 `json:"total_size_in_bytes"` + TotalStoppedTimeInMillis int `json:"total_stopped_time_in_millis"` + TotalThrottledTimeInMillis int `json:"total_throttled_time_in_millis"` + TotalAutoThrottleInBytes int `json:"total_auto_throttle_in_bytes"` + UnreferencedFileCleanupsPerformed int `json:"unreferenced_file_cleanups_performed"` +} + +// IndicesStatsRefresh is a sub type of IndicesStatsInfo containing stats about index refresh +type IndicesStatsRefresh struct { + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + ExternalTotal int `json:"external_total"` + ExternalTotalTimeInMillis int `json:"external_total_time_in_millis"` + Listeners int `json:"listeners"` +} + +// IndicesStatsFlush is a sub type of IndicesStatsInfo containing stats about index flush +type IndicesStatsFlush struct { + Total int `json:"total"` + Periodic int `json:"periodic"` + TotalTimeInMillis int `json:"total_time_in_millis"` +} + +// IndicesStatsWarmer is a sub type of IndicesStatsInfo containing stats about index warmer +type IndicesStatsWarmer struct { + Current int `json:"current"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` +} + +// IndicesStatsQueryCache is a sub type of IndicesStatsInfo containing stats about index query cache +type IndicesStatsQueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` +} + +// IndicesStatsFielddata is a sub type of IndicesStatsInfo containing stats about index fielddata +type IndicesStatsFielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` +} + +// IndicesStatsCompletion is a sub type of IndicesStatsInfo containing stats about index completion +type IndicesStatsCompletion struct { + SizeInBytes int `json:"size_in_bytes"` +} + +// IndicesStatsSegments is a sub type of IndicesStatsInfo containing stats about index segments +type IndicesStatsSegments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int64 `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + Pressure struct { + TotalRejections int `json:"total_rejections"` + } `json:"pressure"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` +} + +// IndicesStatsTranslog is a sub type of IndicesStatsInfo containing stats about index translog +type IndicesStatsTranslog struct { + Operations int `json:"operations"` + SizeInBytes int `json:"size_in_bytes"` + UncommittedOperations int `json:"uncommitted_operations"` + UncommittedSizeInBytes int `json:"uncommitted_size_in_bytes"` + EarliestLastModifiedAge int `json:"earliest_last_modified_age"` + RemoteStore struct { + Upload struct { + TotalUploads struct { + Started int `json:"started"` + Failed int `json:"failed"` + Succeeded int `json:"succeeded"` + } `json:"total_uploads"` + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + FailedBytes int `json:"failed_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + } `json:"total_upload_size"` + } `json:"upload"` + } `json:"remote_store"` +} + +// IndicesStatsRequestCache is a sub type of IndicesStatsInfo containing stats about index request cache +type IndicesStatsRequestCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` +} + +// IndicesStatsRecovery is a sub type of IndicesStatsInfo containing stats about index recovery +type IndicesStatsRecovery struct { + CurrentAsSource int `json:"current_as_source"` + CurrentAsTarget int `json:"current_as_target"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` +} + +// IndicesStatsInfo is a sub type of IndicesStatsAll, IndicesStatsDetails aggregating all document stats +type IndicesStatsInfo struct { + Docs IndicesStatsDocs `json:"docs"` + Store IndicesStatsStore `json:"store"` + Indexing IndicesStatsIndexing `json:"indexing"` + Get IndicesStatsGet `json:"get"` + Search IndicesStatsSearch `json:"search"` + Merges IndicesStatsMerges `json:"merges"` + Refresh IndicesStatsRefresh `json:"refresh"` + Flush IndicesStatsFlush `json:"flush"` + Warmer IndicesStatsWarmer `json:"warmer"` + QueryCache IndicesStatsQueryCache `json:"query_cache"` + Fielddata IndicesStatsFielddata `json:"fielddata"` + Completion IndicesStatsCompletion `json:"completion"` + Segments IndicesStatsSegments `json:"segments"` + Translog IndicesStatsTranslog `json:"translog"` + RequestCache IndicesStatsRequestCache `json:"request_cache"` + Recovery IndicesStatsRecovery `json:"recovery"` +} + +// IndicesStatsAll is a sub type of IndicesStatsResp containing information about docs stats from all indices +type IndicesStatsAll struct { + Primaries IndicesStatsInfo `json:"primaries"` + Total IndicesStatsInfo `json:"total"` +} + +// IndicesStatsDetails is a sub type of IndicesStatsIndices containing the information about the index uuid and index stats +type IndicesStatsDetails struct { + UUID string `json:"uuid"` + Primaries IndicesStatsInfo `json:"primaries"` + Total IndicesStatsInfo `json:"total"` +} + +// IndicesStatsIndices is a sub type of IndicesStatsResp containing information about docs stats from specific indices +type IndicesStatsIndices map[string]IndicesStatsDetails diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate-params.go new file mode 100644 index 0000000000..837db3247e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate-params.go @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesValidateQueryParams represents possible parameters for the IndicesValidateQueryReq +type IndicesValidateQueryParams struct { + AllowNoIndices *bool + AllShards *bool + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + ExpandWildcards string + Explain *bool + IgnoreUnavailable *bool + Lenient *bool + Query string + Rewrite *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IndicesValidateQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.AllShards != nil { + params["all_shards"] = strconv.FormatBool(*r.AllShards) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Rewrite != nil { + params["rewrite"] = strconv.FormatBool(*r.Rewrite) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate.go new file mode 100644 index 0000000000..5ab44462b2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices-validate.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IndicesValidateQueryReq represents possible options for the index shrink request +type IndicesValidateQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesValidateQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesValidateQueryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(17 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_validate/query") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesValidateQueryResp represents the returned struct of the index shrink response +type IndicesValidateQueryResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresShard `json:"failures"` + } `json:"_shards"` + Valid bool `json:"valid"` + Error *string `json:"error"` + Explanations []struct { + Index string `json:"index"` + Shard int `json:"shard"` + Valid bool `json:"valid"` + Explanation *string `json:"explanation"` + Error *string `json:"error"` + } `json:"explanations"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesValidateQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices.go new file mode 100644 index 0000000000..bf332b04ce --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_indices.go @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type indicesClient struct { + apiClient *Client + Alias aliasClient + Mapping mappingClient + Settings settingsClient +} + +// Delete executes a delete indices request with the required IndicesDeleteReq +func (c indicesClient) Delete(ctx context.Context, req IndicesDeleteReq) (*IndicesDeleteResp, error) { + var ( + data IndicesDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Create executes a creade indices request with the required IndicesCreateReq +func (c indicesClient) Create(ctx context.Context, req IndicesCreateReq) (*IndicesCreateResp, error) { + var ( + data IndicesCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists indices request with the required IndicesExistsReq +func (c indicesClient) Exists(ctx context.Context, req IndicesExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Block executes a //_block request with the required IndicesBlockReq +func (c indicesClient) Block(ctx context.Context, req IndicesBlockReq) (*IndicesBlockResp, error) { + var ( + data IndicesBlockResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Analyze executes a //_analyze request with the required IndicesAnalyzeReq +func (c indicesClient) Analyze(ctx context.Context, req IndicesAnalyzeReq) (*IndicesAnalyzeResp, error) { + var ( + data IndicesAnalyzeResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ClearCache executes a //_cache/clear request with the optional IndicesClearCacheReq +func (c indicesClient) ClearCache(ctx context.Context, req *IndicesClearCacheReq) (*IndicesClearCacheResp, error) { + if req == nil { + req = &IndicesClearCacheReq{} + } + + var ( + data IndicesClearCacheResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Clone executes a //_clone/ request with the required IndicesCloneReq +func (c indicesClient) Clone(ctx context.Context, req IndicesCloneReq) (*IndicesCloneResp, error) { + var ( + data IndicesCloneResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Close executes a //_close request with the required IndicesCloseReq +func (c indicesClient) Close(ctx context.Context, req IndicesCloseReq) (*IndicesCloseResp, error) { + var ( + data IndicesCloseResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a / request with the required IndicesGetReq +func (c indicesClient) Get(ctx context.Context, req IndicesGetReq) (*IndicesGetResp, error) { + var ( + data IndicesGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Open executes a //_open request with the required IndicesOpenReq +func (c indicesClient) Open(ctx context.Context, req IndicesOpenReq) (*IndicesOpenResp, error) { + var ( + data IndicesOpenResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Shrink executes a //_shrink/ request with the required IndicesShrinkReq +func (c indicesClient) Shrink(ctx context.Context, req IndicesShrinkReq) (*IndicesShrinkResp, error) { + var ( + data IndicesShrinkResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Split executes a //_split/ request with the required IndicesSplitReq +func (c indicesClient) Split(ctx context.Context, req IndicesSplitReq) (*IndicesSplitResp, error) { + var ( + data IndicesSplitResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Flush executes a //_flush request with the optional IndicesFlushReq +func (c indicesClient) Flush(ctx context.Context, req *IndicesFlushReq) (*IndicesFlushResp, error) { + if req == nil { + req = &IndicesFlushReq{} + } + + var ( + data IndicesFlushResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Forcemerge executes a //_forcemerge request with the optional IndicesForcemergeReq +func (c indicesClient) Forcemerge(ctx context.Context, req *IndicesForcemergeReq) (*IndicesForcemergeResp, error) { + if req == nil { + req = &IndicesForcemergeReq{} + } + + var ( + data IndicesForcemergeResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Recovery executes a //_recovery request with the optional IndicesRecoveryReq +func (c indicesClient) Recovery(ctx context.Context, req *IndicesRecoveryReq) (*IndicesRecoveryResp, error) { + if req == nil { + req = &IndicesRecoveryReq{} + } + + var ( + data IndicesRecoveryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Refresh executes a //_refresh request with the optional IndicesRefreshReq +func (c indicesClient) Refresh(ctx context.Context, req *IndicesRefreshReq) (*IndicesRefreshResp, error) { + if req == nil { + req = &IndicesRefreshReq{} + } + + var ( + data IndicesRefreshResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Rollover executes a //_rollover request with the required IndicesRolloverReq +func (c indicesClient) Rollover(ctx context.Context, req IndicesRolloverReq) (*IndicesRolloverResp, error) { + var ( + data IndicesRolloverResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Segments executes a //_segments request with the optional IndicesSegmentsReq +func (c indicesClient) Segments(ctx context.Context, req *IndicesSegmentsReq) (*IndicesSegmentsResp, error) { + if req == nil { + req = &IndicesSegmentsReq{} + } + + var ( + data IndicesSegmentsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ShardStores executes a //_shard_stores request with the optional IndicesShardStoresReq +func (c indicesClient) ShardStores(ctx context.Context, req *IndicesShardStoresReq) (*IndicesShardStoresResp, error) { + if req == nil { + req = &IndicesShardStoresReq{} + } + + var ( + data IndicesShardStoresResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a //_stats request with the optional IndicesStatsReq +func (c indicesClient) Stats(ctx context.Context, req *IndicesStatsReq) (*IndicesStatsResp, error) { + if req == nil { + req = &IndicesStatsReq{} + } + + var ( + data IndicesStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ValidateQuery executes a //_validate/query request with the required IndicesValidateQueryReq +func (c indicesClient) ValidateQuery(ctx context.Context, req IndicesValidateQueryReq) (*IndicesValidateQueryResp, error) { + var ( + data IndicesValidateQueryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Count executes a //_count request with the required IndicesCountReq +func (c indicesClient) Count(ctx context.Context, req *IndicesCountReq) (*IndicesCountResp, error) { + if req == nil { + req = &IndicesCountReq{} + } + + var ( + data IndicesCountResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// FieldCaps executes a //_field_caps request with the required IndicesFieldCapsReq +func (c indicesClient) FieldCaps(ctx context.Context, req IndicesFieldCapsReq) (*IndicesFieldCapsResp, error) { + var ( + data IndicesFieldCapsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Resolve executes a /_resolve/index/ request with the required IndicesResolveReq +func (c indicesClient) Resolve(ctx context.Context, req IndicesResolveReq) (*IndicesResolveResp, error) { + var ( + data IndicesResolveResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info-params.go new file mode 100644 index 0000000000..d9e4c2483d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// InfoParams represents possible parameters for the InfoReq +type InfoParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r InfoParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info.go new file mode 100644 index 0000000000..fc4ceb4890 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_info.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Info executes a / request with the optional InfoReq +func (c Client) Info(ctx context.Context, req *InfoReq) (*InfoResp, error) { + if req == nil { + req = &InfoReq{} + } + + var ( + data InfoResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// InfoReq represents possible options for the / request +type InfoReq struct { + Header http.Header + Params InfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r InfoReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/", + nil, + r.Params.get(), + r.Header, + ) +} + +// InfoResp represents the returned struct of the / response +type InfoResp struct { + Name string `json:"name"` + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Version struct { + Distribution string `json:"distribution"` + Number string `json:"number"` + BuildType string `json:"build_type"` + BuildHash string `json:"build_hash"` + BuildDate string `json:"build_date"` + BuildSnapshot bool `json:"build_snapshot"` + LuceneVersion string `json:"lucene_version"` + MinimumWireCompatibilityVersion string `json:"minimum_wire_compatibility_version"` + MinimumIndexCompatibilityVersion string `json:"minimum_index_compatibility_version"` + } `json:"version"` + Tagline string `json:"tagline"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r InfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create-params.go new file mode 100644 index 0000000000..98cd30803d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// IngestCreateParams represents possible parameters for the IngestCreateReq +type IngestCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IngestCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create.go new file mode 100644 index 0000000000..f5d7adc105 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IngestCreateReq represents possible options for the index create request +type IngestCreateReq struct { + PipelineID string + + Body io.Reader + + Header http.Header + Params IngestCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_ingest/pipeline/%s", r.PipelineID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IngestCreateResp represents the returned struct of the index create response +type IngestCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete-params.go new file mode 100644 index 0000000000..777c6ae08c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// IngestDeleteParams represents possible parameters for the IngestDeleteReq +type IngestDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IngestDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete.go new file mode 100644 index 0000000000..4e798d8024 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IngestDeleteReq represents possible options for the index create request +type IngestDeleteReq struct { + PipelineID string + + Header http.Header + Params IngestDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_ingest/pipeline/%s", r.PipelineID), + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestDeleteResp represents the returned struct of the index create response +type IngestDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get-params.go new file mode 100644 index 0000000000..b61345bf0a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// IngestGetParams represents possible parameters for the IngestGetReq +type IngestGetParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Summary *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IngestGetParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Summary != nil { + params["summary"] = strconv.FormatBool(*r.Summary) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get.go new file mode 100644 index 0000000000..5ba24e3143 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-get.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IngestGetReq represents possible options for the index create request +type IngestGetReq struct { + PipelineIDs []string + + Header http.Header + Params IngestGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_ingest/pipeline/%s", strings.Join(r.PipelineIDs, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestGetResp represents the returned struct of the index create response +type IngestGetResp struct { + Pipelines map[string]struct { + Description string `json:"description"` + Processors []map[string]json.RawMessage `json:"processors"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok-params.go new file mode 100644 index 0000000000..d67d9239e2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// IngestGrokParams represents possible parameters for the IngestGrokReq +type IngestGrokParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IngestGrokParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok.go new file mode 100644 index 0000000000..a6cdc4b6e9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-grok.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IngestGrokReq represents possible options for the index create request +type IngestGrokReq struct { + Header http.Header + Params IngestGrokParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestGrokReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_ingest/processor/grok", + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestGrokResp represents the returned struct of the index create response +type IngestGrokResp struct { + Patterns map[string]string `json:"patterns"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestGrokResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate-params.go new file mode 100644 index 0000000000..906762d0a1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IngestSimulateParams represents possible parameters for the IngestSimulateReq +type IngestSimulateParams struct { + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r IngestSimulateParams) get() map[string]string { + params := make(map[string]string) + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate.go new file mode 100644 index 0000000000..1aa81e387c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest-simulate.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// IngestSimulateReq represents possible options for the index create request +type IngestSimulateReq struct { + PipelineID string + + Body io.Reader + + Header http.Header + Params IngestSimulateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestSimulateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_ingest/pipeline//_simulate") + len(r.PipelineID)) + path.WriteString("/_ingest/pipeline/") + if len(r.PipelineID) > 0 { + path.WriteString(r.PipelineID) + path.WriteString("/") + } + path.WriteString("_simulate") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IngestSimulateResp represents the returned struct of the index create response +type IngestSimulateResp struct { + Docs []json.RawMessage `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestSimulateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest.go new file mode 100644 index 0000000000..4734a42ab6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ingest.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type ingestClient struct { + apiClient *Client +} + +// Create executes a creade ingest request with the required IngestCreateReq +func (c ingestClient) Create(ctx context.Context, req IngestCreateReq) (*IngestCreateResp, error) { + var ( + data IngestCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete ingest request with the required IngestDeleteReq +func (c ingestClient) Delete(ctx context.Context, req IngestDeleteReq) (*IngestDeleteResp, error) { + var ( + data IngestDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get ingest request with the optional IngestGetReq +func (c ingestClient) Get(ctx context.Context, req *IngestGetReq) (*IngestGetResp, error) { + if req == nil { + req = &IngestGetReq{} + } + + var ( + data IngestGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Pipelines); err != nil { + return &data, err + } + + return &data, nil +} + +// Simulate executes a stats ingest request with the optional IngestSimulateReq +func (c ingestClient) Simulate(ctx context.Context, req IngestSimulateReq) (*IngestSimulateResp, error) { + var ( + data IngestSimulateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Grok executes a get ingest request with the optional IngestGrokReq +func (c ingestClient) Grok(ctx context.Context, req *IngestGrokReq) (*IngestGrokResp, error) { + if req == nil { + req = &IngestGrokReq{} + } + + var ( + data IngestGrokResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget-params.go new file mode 100644 index 0000000000..eeda2e8651 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget-params.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MGetParams represents possible parameters for the MGetReq +type MGetParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget.go new file mode 100644 index 0000000000..11a3067255 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mget.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// MGet executes a /_mget request with the optional MGetReq +func (c Client) MGet(ctx context.Context, req MGetReq) (*MGetResp, error) { + var ( + data MGetResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MGetReq represents possible options for the /_mget request +type MGetReq struct { + Index string + + Body io.Reader + + Header http.Header + Params MGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MGetReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_mget") + len(r.Index)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_mget") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MGetResp represents the returned struct of the /_mget response +type MGetResp struct { + Docs []struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Found bool `json:"found"` + Type string `json:"_type"` + Source json.RawMessage `json:"_source"` + } `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-params.go new file mode 100644 index 0000000000..5e7efc83af --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-params.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MSearchParams represents possible parameters for the MSearchReq +type MSearchParams struct { + CcsMinimizeRoundtrips *bool + MaxConcurrentSearches *int + MaxConcurrentShardRequests *int + PreFilterShardSize *int + RestTotalHitsAsInt *bool + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MSearchParams) get() map[string]string { + params := make(map[string]string) + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.MaxConcurrentSearches != nil { + params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) + } + + if r.MaxConcurrentShardRequests != nil { + params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) + } + + if r.PreFilterShardSize != nil { + params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template-params.go new file mode 100644 index 0000000000..ac6739f578 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template-params.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MSearchTemplateParams represents possible parameters for the MSearchTemplateReq +type MSearchTemplateParams struct { + CcsMinimizeRoundtrips *bool + MaxConcurrentSearches *int + RestTotalHitsAsInt *bool + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MSearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.MaxConcurrentSearches != nil { + params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template.go new file mode 100644 index 0000000000..b6206ef03c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch-template.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// MSearchTemplate executes a /_msearch request with the optional MSearchTemplateReq +func (c Client) MSearchTemplate(ctx context.Context, req MSearchTemplateReq) (*MSearchTemplateResp, error) { + var ( + data MSearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MSearchTemplateReq represents possible options for the /_msearch request +type MSearchTemplateReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MSearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MSearchTemplateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_msearch/template") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_msearch/template") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MSearchTemplateResp represents the returned struct of the /_msearch response +type MSearchTemplateResp struct { + Took int `json:"took"` + Responses []struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore *float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + Status int `json:"status"` + } `json:"responses"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MSearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch.go new file mode 100644 index 0000000000..bfd468a8b3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_msearch.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// MSearch executes a /_msearch request with the optional MSearchReq +func (c Client) MSearch(ctx context.Context, req MSearchReq) (*MSearchResp, error) { + var ( + data MSearchResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MSearchReq represents possible options for the /_msearch request +type MSearchReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MSearchParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MSearchReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_msearch") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_msearch") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MSearchResp represents the returned struct of the /_msearch response +type MSearchResp struct { + Took int `json:"took"` + Responses []struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + Status int `json:"status"` + Aggregations json.RawMessage `json:"aggregations"` + } `json:"responses"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MSearchResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors-params.go new file mode 100644 index 0000000000..706e28e469 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors-params.go @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MTermvectorsParams represents possible parameters for the MTermvectorsReq +type MTermvectorsParams struct { + Fields []string + FieldStatistics *bool + Ids []string + Offsets *bool + Payloads *bool + Positions *bool + Preference string + Realtime *bool + Routing string + TermStatistics *bool + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r MTermvectorsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.FieldStatistics != nil { + params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) + } + + if len(r.Ids) > 0 { + params["ids"] = strings.Join(r.Ids, ",") + } + + if r.Offsets != nil { + params["offsets"] = strconv.FormatBool(*r.Offsets) + } + + if r.Payloads != nil { + params["payloads"] = strconv.FormatBool(*r.Payloads) + } + + if r.Positions != nil { + params["positions"] = strconv.FormatBool(*r.Positions) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.TermStatistics != nil { + params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors.go new file mode 100644 index 0000000000..7c30187f82 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_mtermvectors.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// MTermvectors executes a /_mtermvectors request with the required MTermvectorsReq +func (c Client) MTermvectors(ctx context.Context, req MTermvectorsReq) (*MTermvectorsResp, error) { + var ( + data MTermvectorsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MTermvectorsReq represents possible options for the /_mtermvectors request +type MTermvectorsReq struct { + Index string + + Body io.Reader + + Header http.Header + Params MTermvectorsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MTermvectorsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_mtermvectors") + len(r.Index)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_mtermvectors") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MTermvectorsResp represents the returned struct of the /_mtermvectors response +type MTermvectorsResp struct { + Docs []struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Found bool `json:"found"` + Took int `json:"took"` + Type string `json:"_type"` // Deprecated field + TermVectors json.RawMessage `json:"term_vectors"` + } `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MTermvectorsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads-params.go new file mode 100644 index 0000000000..6655182745 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads-params.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// NodesHotThreadsParams represents possible parameters for the NodesHotThreadsReq +type NodesHotThreadsParams struct { + IgnoreIdleThreads *bool + Interval time.Duration + Snapshots *int + Threads *int + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r NodesHotThreadsParams) get() map[string]string { + params := make(map[string]string) + + if r.IgnoreIdleThreads != nil { + params["ignore_idle_threads"] = strconv.FormatBool(*r.IgnoreIdleThreads) + } + + if r.Interval != 0 { + params["interval"] = formatDuration(r.Interval) + } + + if r.Snapshots != nil { + params["snapshots"] = strconv.FormatInt(int64(*r.Snapshots), 10) + } + + if r.Threads != nil { + params["threads"] = strconv.FormatInt(int64(*r.Threads), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads.go new file mode 100644 index 0000000000..080e5422eb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-hot_threads.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// NodesHotThreadsReq represents possible options for the /_nodes request +type NodesHotThreadsReq struct { + NodeID []string + + Header http.Header + Params NodesHotThreadsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesHotThreadsReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + + var path strings.Builder + path.Grow(len("/_nodes//hot_threads") + len(nodes)) + path.WriteString("/_nodes/") + if len(r.NodeID) > 0 { + path.WriteString(nodes) + path.WriteString("/") + } + path.WriteString("hot_threads") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info-params.go new file mode 100644 index 0000000000..1ec2129881 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info-params.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// NodesInfoParams represents possible parameters for the NodesInfoReq +type NodesInfoParams struct { + FlatSettings *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r NodesInfoParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info.go new file mode 100644 index 0000000000..9d89b0648c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-info.go @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// NodesInfoReq represents possible options for the /_nodes request +type NodesInfoReq struct { + Metrics []string + NodeID []string + + Header http.Header + Params NodesInfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesInfoReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//") + len(nodes) + len(metrics)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + if len(r.Metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesInfoResp represents the returned struct of the /_nodes response +type NodesInfoResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresCause `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesInfo `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesInfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesInfo is a sub type of NodesInfoResp containing information about nodes and their stats +type NodesInfo struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Version string `json:"version"` + BuildType string `json:"build_type"` + BuildHash string `json:"build_hash"` + TotalIndexingBuffer int64 `json:"total_indexing_buffer"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Settings json.RawMessage `json:"settings"` // Won't parse as it may contain fields that we can't know + OS NodesInfoOS `json:"os"` + Process NodesInfoProcess `json:"process"` + JVM NodesInfoJVM `json:"jvm"` + ThreadPool map[string]NodesInfoThreadPool `json:"thread_pool"` + Transport NodesInfoTransport `json:"transport"` + HTTP NodesInfoHTTP `json:"http"` + Plugins []NodesInfoPlugin `json:"plugins"` + Modules []NodesInfoPlugin `json:"modules"` + Ingest NodesInfoIngest `json:"ingest"` + Aggregations map[string]NodesInfoAgg `json:"aggregations"` + SearchPipelines NodesInfoSearchPipelines `json:"search_pipelines"` +} + +// NodesInfoOS is a sub type of NodesInfo containing information about the Operating System +type NodesInfoOS struct { + RefreshIntervalInMillis int `json:"refresh_interval_in_millis"` + Name string `json:"name"` + PrettyName string `json:"pretty_name"` + Arch string `json:"arch"` + Version string `json:"version"` + AvailableProcessors int `json:"available_processors"` + AllocatedProcessors int `json:"allocated_processors"` +} + +// NodesInfoProcess is a sub type of NodesInfo containing information about the nodes process +type NodesInfoProcess struct { + RefreshIntervalInMillis int `json:"refresh_interval_in_millis"` + ID int `json:"id"` + Mlockall bool `json:"mlockall"` +} + +// NodesInfoJVM is a sub type of NodesInfo containing information and stats about JVM +type NodesInfoJVM struct { + PID int `json:"pid"` + Version string `json:"version"` + VMName string `json:"vm_name"` + VMVersion string `json:"vm_version"` + VMVendor string `json:"vm_vendor"` + BundledJDK bool `json:"bundled_jdk"` + UsingBundledJDK bool `json:"using_bundled_jdk"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + Mem struct { + HeapInitInBytes int64 `json:"heap_init_in_bytes"` + HeapMaxInBytes int64 `json:"heap_max_in_bytes"` + NonHeapInitInBytes int `json:"non_heap_init_in_bytes"` + NonHeapMaxInBytes int `json:"non_heap_max_in_bytes"` + DirectMaxInBytes int `json:"direct_max_in_bytes"` + } `json:"mem"` + GcCollectors []string `json:"gc_collectors"` + MemoryPools []string `json:"memory_pools"` + UsingCompressedOrdinaryObjectPointers string `json:"using_compressed_ordinary_object_pointers"` + InputArguments []string `json:"input_arguments"` +} + +// NodesInfoThreadPool is a sub type of NodesInfo containing information about a thread pool +type NodesInfoThreadPool struct { + Type string `json:"type"` + Size int `json:"size"` + QueueSize int `json:"queue_size"` + KeepAlive string `json:"keep_alive"` + Max int `json:"max"` + Core int `json:"core"` +} + +// NodesInfoTransport is a sub type of NodesInfo containing information about the nodes transport settings +type NodesInfoTransport struct { + BoundAddress []string `json:"bound_address"` + PublishAddress string `json:"publish_address"` + Profiles json.RawMessage `json:"profiles"` // Unknown content +} + +// NodesInfoHTTP is a sub type of NodesInfo containing information about the nodes http settings +type NodesInfoHTTP struct { + BoundAddress []string `json:"bound_address"` + PublishAddress string `json:"publish_address"` + MaxContentLengthInBytes int64 `json:"max_content_length_in_bytes"` +} + +// NodesInfoPlugin is a sub type of NodesInfo containing information about a plugin +type NodesInfoPlugin struct { + Name string `json:"name"` + Version string `json:"version"` + OpensearchVersion string `json:"opensearch_version"` + JavaVersion string `json:"java_version"` + Description string `json:"description"` + Classname string `json:"classname"` + CustomFoldername *string `json:"custom_foldername"` + ExtendedPlugins []string `json:"extended_plugins"` + HasNativeController bool `json:"has_native_controller"` + OptionalExtendedPlugins []string `json:"optional_extended_plugins"` +} + +// NodesInfoIngest is a sub type of NodesInfo containing information about ingest processors +type NodesInfoIngest struct { + Processors []NodesInfoType `json:"processors"` +} + +// NodesInfoAgg is a sub type of NodesInfo containing information about aggregations +type NodesInfoAgg struct { + Types []string `json:"types"` +} + +// NodesInfoSearchPipelines is a sub type of NodesInfo containing information about search pipelines +type NodesInfoSearchPipelines struct { + RequestProcessors []NodesInfoType `json:"request_processors"` + ResponseProcessors []NodesInfoType `json:"response_processors"` + Processors []NodesInfoType `json:"processors,omitempty"` // Deprecated field only available in 2.7.0 +} + +// NodesInfoType is a sub type of NodesInfoIngest, NodesInfoSearchPipelines containing information about a type +type NodesInfoType struct { + Type string `json:"type"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security-params.go new file mode 100644 index 0000000000..ed42e317b2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// NodesReloadSecurityParams represents possible parameters for the NodesReloadSecurityReq +type NodesReloadSecurityParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r NodesReloadSecurityParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security.go new file mode 100644 index 0000000000..a3ca438d3a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-reload_security.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// NodesReloadSecurityReq represents possible options for the /_nodes request +type NodesReloadSecurityReq struct { + NodeID []string + + Body io.Reader + + Header http.Header + Params NodesReloadSecurityParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesReloadSecurityReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//reload_secure_settings") + len(nodes)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + path.WriteString("/reload_secure_settings") + + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// NodesReloadSecurityResp represents the returned struct of the /_nodes response +type NodesReloadSecurityResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresCause `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]struct { + Name string `json:"name"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesReloadSecurityResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats-params.go new file mode 100644 index 0000000000..775ad5ede8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats-params.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// NodesStatsParams represents possible parameters for the NodesStatsReq +type NodesStatsParams struct { + CompletionFields []string + FielddataFields []string + Fields []string + Groups *bool + IncludeSegmentFileSizes *bool + IncludeUnloadedSegments *bool + Level string + Timeout time.Duration + Types []string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r NodesStatsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.CompletionFields) > 0 { + params["completion_fields"] = strings.Join(r.CompletionFields, ",") + } + + if len(r.FielddataFields) > 0 { + params["fielddata_fields"] = strings.Join(r.FielddataFields, ",") + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.Groups != nil { + params["groups"] = strconv.FormatBool(*r.Groups) + } + + if r.IncludeSegmentFileSizes != nil { + params["include_segment_file_sizes"] = strconv.FormatBool(*r.IncludeSegmentFileSizes) + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Level != "" { + params["level"] = r.Level + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if len(r.Types) > 0 { + params["types"] = strings.Join(r.Types, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats.go new file mode 100644 index 0000000000..782a8982a7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-stats.go @@ -0,0 +1,738 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// NodesStatsReq represents possible options for the /_nodes request +type NodesStatsReq struct { + IndexMetric []string + Metric []string + NodeID []string + Header http.Header + Params NodesStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesStatsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + + path.Grow(13 + len(strings.Join(r.NodeID, ",")) + 1 + len(strings.Join(r.Metric, ",")) + 1 + len(strings.Join(r.IndexMetric, ","))) + + path.WriteString("/") + path.WriteString("_nodes") + + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.NodeID, ",")) + } + + path.WriteString("/") + path.WriteString("stats") + + if len(r.Metric) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.Metric, ",")) + } + + if len(r.IndexMetric) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.IndexMetric, ",")) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesStatsResp represents the returned struct of the /_nodes response +type NodesStatsResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresCause `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesStats `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesStats is a map item of NodesStatsResp representing all values of a node +type NodesStats struct { + Timestamp int `json:"timestamp"` + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Indices NodesStatsIndices `json:"indices"` + OS NodesStatsOS `json:"os"` + Process NodesStatsProcess `json:"process"` + JVM NodesStatsJVM `json:"jvm"` + ThreadPool NodesStatsThreadPool `json:"thread_pool"` + FS NodesStatsFS `json:"fs"` + Transport NodesStatsTransport `json:"transport"` + HTTP NodesStatsHTTP `json:"http"` + Breakers NodesStatsBreakers `json:"breakers"` + Scripts NodesStatsScript `json:"script"` + Discovery NodesStatsDiscovery `json:"discovery"` + Ingest NodesStatsIngest `json:"ingest"` + AdaptiveSelection NodesStatsAdaptiveSelection `json:"adaptive_selection"` + ScriptCache NodesStatsScriptCache `json:"script_cache"` + IndexingPressure NodesStatsIndexingPressure `json:"indexing_pressure"` + ShardIndexingPressure NodesStatsShardIndexingPressure `json:"shard_indexing_pressure"` + SearchBackpressure NodesStatsSearchBackpressure `json:"search_backpressure"` + ClusterManagerThrottling NodesStatsClusterManagerThrottling `json:"cluster_manager_throttling"` + WeightedRouting NodesStatsWeightedRouting `json:"weighted_routing"` + SearchPipeline NodesStatsSearchPipeline `json:"search_pipeline"` + TaskCancellation NodesStatsTaskCancellation `json:"task_cancellation"` + ResourceUsageStats map[string]NodesStatsResourceUsageStats `json:"resource_usage_stats"` + SegmentReplicationBackpressure NodesStatsSegmentReplicationBackpressure `json:"segment_replication_backpressure"` + Repositories []json.RawMessage `json:"repositories"` + AdmissionControl NodesStatsAdmissionControl `json:"admission_control"` + Caches NodesStatsCaches `json:"caches"` + RemoteStore NodeStatsRemoteStore `json:"remote_store"` +} + +// NodesStatsIndices is a sub type of NodesStats representing Indices information of the node +type NodesStatsIndices struct { + Docs struct { + Count int `json:"count"` + Deleted int `json:"deleted"` + } `json:"docs"` + Store struct { + SizeInBytes int `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` + } `json:"store"` + Indexing struct { + IndexTotal int `json:"index_total"` + IndexTimeInMillis int `json:"index_time_in_millis"` + IndexCurrent int `json:"index_current"` + IndexFailed int `json:"index_failed"` + DeleteTotal int `json:"delete_total"` + DeleteTimeInMillis int `json:"delete_time_in_millis"` + DeleteCurrent int `json:"delete_current"` + NoopUpdateTotal int `json:"noop_update_total"` + IsThrottled bool `json:"is_throttled"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + DocStatus map[string]int `json:"doc_status"` + } `json:"indexing"` + Get struct { + Total int `json:"total"` + TimeInMillis int `json:"time_in_millis"` + ExistsTotal int `json:"exists_total"` + ExistsTimeInMillis int `json:"exists_time_in_millis"` + MissingTotal int `json:"missing_total"` + MissingTimeInMillis int `json:"missing_time_in_millis"` + Current int `json:"current"` + GetTime string `json:"getTime"` + } `json:"get"` + Search struct { + OpenContexts int `json:"open_contexts"` + QueryTotal int `json:"query_total"` + QueryTimeInMillis int `json:"query_time_in_millis"` + QueryCurrent int `json:"query_current"` + ConcurrentQueryTotal int `json:"concurrent_query_total"` + ConcurrentQueryTimeInMillis int `json:"concurrent_query_time_in_millis"` + ConcurrentQueryCurrent int `json:"concurrent_query_current"` + ConcurrentAVGSliceCount float32 `json:"concurrent_avg_slice_count"` + FetchTotal int `json:"fetch_total"` + FetchTimeInMillis int `json:"fetch_time_in_millis"` + FetchCurrent int `json:"fetch_current"` + ScrollTotal int `json:"scroll_total"` + ScrollTimeInMillis int `json:"scroll_time_in_millis"` + ScrollCurrent int `json:"scroll_current"` + PointInTimeTotal int `json:"point_in_time_total"` + PointInTimeTimeInMillis int `json:"point_in_time_time_in_millis"` + PointInTimeCurrent int `json:"point_in_time_current"` + SuggestTotal int `json:"suggest_total"` + SuggestTimeInMillis int `json:"suggest_time_in_millis"` + SuggestCurrent int `json:"suggest_current"` + IdleReactivateCountTotal int `json:"search_idle_reactivate_count_total"` + Request struct { + DfsPreQuery NodesStatsIndicesSearchRequest `json:"dfs_pre_query"` + Query NodesStatsIndicesSearchRequest `json:"query"` + Fetch NodesStatsIndicesSearchRequest `json:"fetch"` + DfsQuery NodesStatsIndicesSearchRequest `json:"dfs_query"` + Expand NodesStatsIndicesSearchRequest `json:"expand"` + CanMatch NodesStatsIndicesSearchRequest `json:"can_match"` + Took NodesStatsIndicesSearchRequest `json:"took"` + } `json:"request"` + } `json:"search"` + Merges struct { + Current int `json:"current"` + CurrentDocs int `json:"current_docs"` + CurrentSizeInBytes int `json:"current_size_in_bytes"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + TotalDocs int `json:"total_docs"` + TotalSizeInBytes int `json:"total_size_in_bytes"` + TotalStoppedTimeInMillis int `json:"total_stopped_time_in_millis"` + TotalThrottledTimeInMillis int `json:"total_throttled_time_in_millis"` + TotalAutoThrottleInBytes int `json:"total_auto_throttle_in_bytes"` + UnreferencedFileCleanupsPerformed int `json:"unreferenced_file_cleanups_performed"` + } `json:"merges"` + Refresh struct { + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + ExternalTotal int `json:"external_total"` + ExternalTotalTimeInMillis int `json:"external_total_time_in_millis"` + Listeners int `json:"listeners"` + } `json:"refresh"` + Flush struct { + Total int `json:"total"` + Periodic int `json:"periodic"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"flush"` + Warmer struct { + Current int `json:"current"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"warmer"` + QueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` + } `json:"query_cache"` + Fielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + } `json:"fielddata"` + Completion struct { + SizeInBytes int `json:"size_in_bytes"` + } `json:"completion"` + Segments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + Pressure struct { + TotalRejections int `json:"total_rejections"` + } `json:"pressure"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` + } `json:"segments"` + Translog struct { + Operations int `json:"operations"` + SizeInBytes int `json:"size_in_bytes"` + UncommittedOperations int `json:"uncommitted_operations"` + UncommittedSizeInBytes int `json:"uncommitted_size_in_bytes"` + EarliestLastModifiedAge int `json:"earliest_last_modified_age"` + RemoteStore struct { + Upload struct { + TotalUploads struct { + Started int `json:"started"` + Failed int `json:"failed"` + Succeeded int `json:"succeeded"` + } `json:"total_uploads"` + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + FailedBytes int `json:"failed_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + } `json:"total_upload_size"` + } `json:"upload"` + } `json:"remote_store"` + } `json:"translog"` + RequestCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + } `json:"request_cache"` + Recovery struct { + CurrentAsSource int `json:"current_as_source"` + CurrentAsTarget int `json:"current_as_target"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + } `json:"recovery"` +} + +// NodesStatsOS is a sub type of NodesStats representing operating system information of the node +type NodesStatsOS struct { + Timestamp int `json:"timestamp"` + CPU struct { + Percent int `json:"percent"` + LoadAverage struct { + OneM float64 `json:"1m"` + FiveM float64 `json:"5m"` + One5M float64 `json:"15m"` + } `json:"load_average"` + } `json:"cpu"` + Mem struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + UsedInBytes int `json:"used_in_bytes"` + FreePercent int `json:"free_percent"` + UsedPercent int `json:"used_percent"` + } `json:"mem"` + Swap struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + UsedInBytes int `json:"used_in_bytes"` + } `json:"swap"` +} + +// NodesStatsProcess is a sub type of NodesStats representing processor information of the node +type NodesStatsProcess struct { + Timestamp int `json:"timestamp"` + OpenFileDescriptors int `json:"open_file_descriptors"` + MaxFileDescriptors int `json:"max_file_descriptors"` + CPU struct { + Percent int `json:"percent"` + TotalInMillis int `json:"total_in_millis"` + } `json:"cpu"` + Mem struct { + TotalVirtualInBytes int `json:"total_virtual_in_bytes"` + } `json:"mem"` +} + +// NodesStatsJVMPool is a sub type of NodesStatsJVM represeting all information a pool can have +type NodesStatsJVMPool struct { + UsedInBytes int `json:"used_in_bytes"` + MaxInBytes int `json:"max_in_bytes"` + PeakUsedInBytes int `json:"peak_used_in_bytes"` + PeakMaxInBytes int `json:"peak_max_in_bytes"` + LastGcStats struct { + UsedInBytes int `json:"used_in_bytes"` + MaxInBytes int `json:"max_in_bytes"` + UsagePercent int `json:"usage_percent"` + } `json:"last_gc_stats"` +} + +// NodesStatsJVMBufferPool is a sub map type represeting all information a buffer pool can have +type NodesStatsJVMBufferPool struct { + Count int `json:"count"` + UsedInBytes int `json:"used_in_bytes"` + TotalCapacityInBytes int `json:"total_capacity_in_bytes"` +} + +// NodesStatsJVM is a sub type of NodesStats representing java virtual maschine information of the node +type NodesStatsJVM struct { + Timestamp int `json:"timestamp"` + UptimeInMillis int `json:"uptime_in_millis"` + Mem struct { + HeapUsedInBytes int `json:"heap_used_in_bytes"` + HeapUsedPercent int `json:"heap_used_percent"` + HeapCommittedInBytes int `json:"heap_committed_in_bytes"` + HeapMaxInBytes int `json:"heap_max_in_bytes"` + NonHeapUsedInBytes int `json:"non_heap_used_in_bytes"` + NonHeapCommittedInBytes int `json:"non_heap_committed_in_bytes"` + Pools struct { + Young NodesStatsJVMPool `json:"young"` + Old NodesStatsJVMPool `json:"old"` + Survivor NodesStatsJVMPool `json:"survivor"` + } `json:"pools"` + } `json:"mem"` + Threads struct { + Count int `json:"count"` + PeakCount int `json:"peak_count"` + } `json:"threads"` + Gc struct { + Collectors map[string]NodesStatsJVMGCCollectors `json:"collectors"` + } `json:"gc"` + // Not parsing each field directly as one of them contains singe quotes which are not allowed as tag in golang json + // https://github.com/golang/go/issues/22518 + BufferPools map[string]NodesStatsJVMBufferPool `json:"buffer_pools"` + Classes struct { + CurrentLoadedCount int `json:"current_loaded_count"` + TotalLoadedCount int `json:"total_loaded_count"` + TotalUnloadedCount int `json:"total_unloaded_count"` + } `json:"classes"` +} + +// NodesStatsJVMGCCollectors is a sub type of NodesStatsJVM containing collector information +type NodesStatsJVMGCCollectors struct { + CollectionCount int `json:"collection_count"` + CollectionTimeInMillis int `json:"collection_time_in_millis"` +} + +// NodesStatsThreadPoolValues is a sub type of NodesStatsThreadPool representing all information a thread pool can have +type NodesStatsThreadPoolValues struct { + Threads int `json:"threads"` + Queue int `json:"queue"` + Active int `json:"active"` + Rejected int `json:"rejected"` + Largest int `json:"largest"` + Completed int `json:"completed"` + TotalWaitTimeInNanos *int64 `json:"total_wait_time_in_nanos,omitempty"` +} + +// NodesStatsThreadPool is a sub type of NodesStats representing thread pool information of the node +type NodesStatsThreadPool map[string]NodesStatsThreadPoolValues + +// NodesStatsFS is a sub type of NodesStats representing filesystem information of the node +type NodesStatsFS struct { + Timestamp int `json:"timestamp"` + Total struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + AvailableInBytes int `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"total"` + Data []struct { + Path string `json:"path"` + Mount string `json:"mount"` + Type string `json:"type"` + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + AvailableInBytes int `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"data"` + IoStats struct { + Devices []struct { + DeviceName string `json:"device_name"` + Operations int `json:"operations"` + ReadOperations int `json:"read_operations"` + WriteOperations int `json:"write_operations"` + ReadKilobytes int `json:"read_kilobytes"` + WriteKilobytes int `json:"write_kilobytes"` + } `json:"devices"` + Total struct { + Operations int `json:"operations"` + ReadOperations int `json:"read_operations"` + WriteOperations int `json:"write_operations"` + ReadKilobytes int `json:"read_kilobytes"` + WriteKilobytes int `json:"write_kilobytes"` + } `json:"total"` + } `json:"io_stats"` +} + +// NodesStatsTransport is a sub type of NodesStats representing network transport information of the node +type NodesStatsTransport struct { + ServerOpen int `json:"server_open"` + TotalOutboundConnections int `json:"total_outbound_connections"` + RxCount int `json:"rx_count"` + RxSizeInBytes int `json:"rx_size_in_bytes"` + TxCount int `json:"tx_count"` + TxSizeInBytes int `json:"tx_size_in_bytes"` +} + +// NodesStatsHTTP is a sub type of NodesStats representing http information of the node +type NodesStatsHTTP struct { + CurrentOpen int `json:"current_open"` + TotalOpened int `json:"total_opened"` +} + +// NodesStatsBreaker is a sub type of NodesStatsBreakers containing all information a breaker can have +type NodesStatsBreaker struct { + LimitSizeInBytes int `json:"limit_size_in_bytes"` + LimitSize string `json:"limit_size"` + EstimatedSizeInBytes int `json:"estimated_size_in_bytes"` + EstimatedSize string `json:"estimated_size"` + Overhead float64 `json:"overhead"` + Tripped int `json:"tripped"` +} + +// NodesStatsBreakers is a sub type of NodesStats representing breakers information of the node +type NodesStatsBreakers struct { + Accounting NodesStatsBreaker `json:"accounting"` + Request NodesStatsBreaker `json:"request"` + Fielddata NodesStatsBreaker `json:"fielddata"` + InFlightRequests NodesStatsBreaker `json:"in_flight_requests"` + Parent NodesStatsBreaker `json:"parent"` +} + +// NodesStatsScript is a sub type of NodesStats representing script information of the node +type NodesStatsScript struct { + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` +} + +// NodesStatsDiscovery is a sub type of NodesStats representing discovery information of the node +type NodesStatsDiscovery struct { + ClusterStateQueue struct { + Total int `json:"total"` + Pending int `json:"pending"` + Committed int `json:"committed"` + } `json:"cluster_state_queue"` + PublishedClusterStates struct { + FullStates int `json:"full_states"` + IncompatibleDiffs int `json:"incompatible_diffs"` + CompatibleDiffs int `json:"compatible_diffs"` + } `json:"published_cluster_states"` + ClusterStateStats struct { + Overall struct { + UpdateCount int `json:"update_count"` + TotalTimeInMillis int `json:"total_time_in_millis"` + FailedCount int `json:"failed_count"` + } `json:"overall"` + } `json:"cluster_state_stats"` +} + +// NodesStatsIngestDetails is a sub map type of NodsStatsIngest containing all information of ingest pipelines +type NodesStatsIngestDetails struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Failed int `json:"failed"` + Current int `json:"current"` + Processors []json.RawMessage `json:"processors"` +} + +// NodesStatsIngest is a sub type of NodesStats representing ingest pipelines information of the node +type NodesStatsIngest struct { + Total struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total"` + Pipelines map[string]NodesStatsIngestDetails `json:"pipelines"` +} + +// NodesStatsAdaptiveSelection is a sub type of NodesStats representing adaptive selection information of the node +type NodesStatsAdaptiveSelection map[string]struct { + OutgoingSearches int `json:"outgoing_searches"` + AvgQueueSize int `json:"avg_queue_size"` + AvgServiceTimeNs int `json:"avg_service_time_ns"` + AvgResponseTimeNs int `json:"avg_response_time_ns"` + Rank string `json:"rank"` +} + +// NodesStatsScriptCache is a sub type of NodesStats representing script cache information of the node +type NodesStatsScriptCache struct { + Sum struct { + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` + } `json:"sum"` + Contexts []struct { + Context string `json:"context"` + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` + } `json:"contexts"` +} + +// NodesStatsIndexingPressure is a sub type of NodesStats representing indexing pressure information of the node +type NodesStatsIndexingPressure struct { + Memory struct { + Current struct { + CombinedCoordinatingAndPrimaryInBytes int `json:"combined_coordinating_and_primary_in_bytes"` + CoordinatingInBytes int `json:"coordinating_in_bytes"` + PrimaryInBytes int `json:"primary_in_bytes"` + ReplicaInBytes int `json:"replica_in_bytes"` + AllInBytes int `json:"all_in_bytes"` + } `json:"current"` + Total struct { + CombinedCoordinatingAndPrimaryInBytes int `json:"combined_coordinating_and_primary_in_bytes"` + CoordinatingInBytes int `json:"coordinating_in_bytes"` + PrimaryInBytes int `json:"primary_in_bytes"` + ReplicaInBytes int `json:"replica_in_bytes"` + AllInBytes int `json:"all_in_bytes"` + CoordinatingRejections int `json:"coordinating_rejections"` + PrimaryRejections int `json:"primary_rejections"` + ReplicaRejections int `json:"replica_rejections"` + } `json:"total"` + LimitInBytes int `json:"limit_in_bytes"` + } `json:"memory"` +} + +// NodesStatsShardIndexingPressure is a sub type of NodesStats representing shard indexing pressure information of the node +type NodesStatsShardIndexingPressure struct { + Stats json.RawMessage `json:"stats"` // Unknown, can be added if you have an example + TotalRejectionsBreakupShadowMode struct { + NodeLimits int `json:"node_limits"` + NoSuccessfulRequestLimits int `json:"no_successful_request_limits"` + ThroughputDegradationLimits int `json:"throughput_degradation_limits"` + } `json:"total_rejections_breakup_shadow_mode"` + Enabled bool `json:"enabled"` + Enforced bool `json:"enforced"` +} + +// NodesStatsSearchBackpressureTracker is a sub type of NodesStatsSearchBrackpressure containing all information of a tracker +type NodesStatsSearchBackpressureTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxMillis int `json:"current_max_millis"` + CurrentAvgMillis int `json:"current_avg_millis"` +} + +// NodesStatsSearchBackpressure is a sub type of NodesStats representing search packbressure information of a node +type NodesStatsSearchBackpressure struct { + SearchTask struct { + ResourceTrackerStats struct { + CPUUsageTracker NodesStatsSearchBackpressureTracker `json:"cpu_usage_tracker"` + ElapsedTimeTracker NodesStatsSearchBackpressureTracker `json:"elapsed_time_tracker"` + HeapUsageTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxBytes int `json:"current_max_bytes"` + CurrentAvgBytes int `json:"current_avg_bytes"` + RollingAvgBytes int `json:"rolling_avg_bytes"` + } `json:"heap_usage_tracker"` + } `json:"resource_tracker_stats"` + CancellationStats struct { + CancellationCount int `json:"cancellation_count"` + CancellationLimitReachedCount int `json:"cancellation_limit_reached_count"` + } `json:"cancellation_stats"` + } `json:"search_task"` + SearchShardTask struct { + ResourceTrackerStats struct { + CPUUsageTracker NodesStatsSearchBackpressureTracker `json:"cpu_usage_tracker"` + ElapsedTimeTracker NodesStatsSearchBackpressureTracker `json:"elapsed_time_tracker"` + HeapUsageTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxBytes int `json:"current_max_bytes"` + CurrentAvgBytes int `json:"current_avg_bytes"` + RollingAvgBytes int `json:"rolling_avg_bytes"` + } `json:"heap_usage_tracker"` + } `json:"resource_tracker_stats"` + CancellationStats struct { + CancellationCount int `json:"cancellation_count"` + CancellationLimitReachedCount int `json:"cancellation_limit_reached_count"` + } `json:"cancellation_stats"` + } `json:"search_shard_task"` + Mode string `json:"mode"` +} + +// NodesStatsClusterManagerThrottling is a sub type of NodesStats representing cluster manager throttling information of the node +type NodesStatsClusterManagerThrottling struct { + Stats struct { + TotalThrottledTasks int `json:"total_throttled_tasks"` + ThrottledTasksPerTaskType json.RawMessage `json:"throttled_tasks_per_task_type"` // Unknow struct, no example in doc + } `json:"stats"` +} + +// NodesStatsWeightedRouting is a sub type of NodesStats representing weighted routing information of the node +type NodesStatsWeightedRouting struct { + Stats struct { + FailOpenCount int `json:"fail_open_count"` + } `json:"stats"` +} + +// NodesStatsSearchPipeline is a sub type of NodesStats containing stats about search pipelines +type NodesStatsSearchPipeline struct { + TotalRequest struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total_request"` + TotalResponse struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total_response"` + Pipelines json.RawMessage `json:"pipelines"` +} + +// NodesStatsTaskCancellation is a sub type of NodesStats containing stats about canceled tasks +type NodesStatsTaskCancellation struct { + SearchShardTask struct { + CurrentCountPostCancel int `json:"current_count_post_cancel"` + TotalCountPostCancel int `json:"total_count_post_cancel"` + } `json:"search_shard_task"` +} + +// NodesStatsIndicesSearchRequest is a sub type of NodesStatsIndices containing stats about search requests +type NodesStatsIndicesSearchRequest struct { + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Total int `json:"total"` +} + +// NodesStatsResourceUsageStats is a sub type of NodesStats containing nodes resource information +type NodesStatsResourceUsageStats struct { + Timestamp int64 `json:"timestamp"` + CPUUtilizationPercent string `json:"cpu_utilization_percent"` + MemoryUtilizationPercent string `json:"memory_utilization_percent"` + IOUsageStats struct { + MaxIOUtilizationPercent string `json:"max_io_utilization_percent"` + } `json:"io_usage_stats"` +} + +// NodesStatsSegmentReplicationBackpressure is a sub type of NodesStats containing information about segment replication backpressure +type NodesStatsSegmentReplicationBackpressure struct { + TotalRejectedRequests int `json:"total_rejected_requests"` +} + +// NodesStatsAdmissionControl is a sub type of NodesStats +type NodesStatsAdmissionControl struct { + GlobalCPUUsage struct { + Transport struct { + RejectionCount json.RawMessage `json:"rejection_count"` + } `json:"transport"` + } `json:"global_cpu_usage"` + GlobalIOUsage struct { + Transport struct { + RejectionCount json.RawMessage `json:"rejection_count"` + } `json:"transport"` + } `json:"global_io_usage"` +} + +// NodesStatsCaches is a sub type of NodesStats +type NodesStatsCaches struct { + RequestCache struct { + SizeInBytes int `json:"size_in_bytes"` + Evictions int `json:"evictions"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + ItemCount int `json:"item_count"` + StoreName string `json:"store_name"` + } `json:"request_cache"` +} + +// NodeStatsRemoteStore is a sub type of NodesStats +type NodeStatsRemoteStore struct { + LastSuccessfulFetchOfPinnedTimestamps int `json:"last_successful_fetch_of_pinned_timestamps"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage-params.go new file mode 100644 index 0000000000..956477f04a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// NodesUsageParams represents possible parameters for the NodesUsageReq +type NodesUsageParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r NodesUsageParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage.go new file mode 100644 index 0000000000..8f3a678faf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes-usage.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// NodesUsageReq represents possible options for the /_nodes request +type NodesUsageReq struct { + Metrics []string + NodeID []string + + Header http.Header + Params NodesUsageParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesUsageReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//usage/") + len(nodes) + len(metrics)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + path.WriteString("/usage") + if len(r.Metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesUsageResp represents the returned struct of the /_nodes response +type NodesUsageResp struct { + NodesUsage struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []FailuresCause `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesUsage `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesUsageResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesUsage is a sub type of NodesUsageResp containing stats about rest api actions +type NodesUsage struct { + Timestamp int64 `json:"timestamp"` + Since int64 `json:"since"` + RestActions map[string]int `json:"rest_actions"` + Aggregations json.RawMessage `json:"aggregations"` // Can contain unknow fields +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes.go new file mode 100644 index 0000000000..8de0fc75a2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_nodes.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type nodesClient struct { + apiClient *Client +} + +// Stats executes a /_nodes/_stats request with the optional NodesStatsReq +func (c nodesClient) Stats(ctx context.Context, req *NodesStatsReq) (*NodesStatsResp, error) { + if req == nil { + req = &NodesStatsReq{} + } + + var ( + data NodesStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Info executes a /_nodes request with the optional NodesInfoReq +func (c nodesClient) Info(ctx context.Context, req *NodesInfoReq) (*NodesInfoResp, error) { + if req == nil { + req = &NodesInfoReq{} + } + + var ( + data NodesInfoResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// HotThreads executes a /_nodes/hot_threads request with the optional NodesHotThreadsReq +func (c nodesClient) HotThreads(ctx context.Context, req *NodesHotThreadsReq) (*opensearch.Response, error) { + if req == nil { + req = &NodesHotThreadsReq{} + } + return c.apiClient.do(ctx, req, nil) +} + +// ReloadSecurity executes a /_nodes/reload_secure_settings request with the optional NodesReloadSecurityReq +func (c nodesClient) ReloadSecurity(ctx context.Context, req *NodesReloadSecurityReq) (*NodesReloadSecurityResp, error) { + if req == nil { + req = &NodesReloadSecurityReq{} + } + + var ( + data NodesReloadSecurityResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Usage executes a /_nodes/usage request with the optional NodesUsageReq +func (c nodesClient) Usage(ctx context.Context, req *NodesUsageReq) (*NodesUsageResp, error) { + if req == nil { + req = &NodesUsageReq{} + } + + var ( + data NodesUsageResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping-params.go new file mode 100644 index 0000000000..aac23a980a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// PingParams represents possible parameters for the PingReq +type PingParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r PingParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping.go new file mode 100644 index 0000000000..15a206cf94 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_ping.go @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Ping executes a / request with the optional PingReq +func (c Client) Ping(ctx context.Context, req *PingReq) (*opensearch.Response, error) { + if req == nil { + req = &PingReq{} + } + + return c.do(ctx, req, nil) +} + +// PingReq represents possible options for the / request +type PingReq struct { + Header http.Header + Params PingParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PingReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + "/", + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create-params.go new file mode 100644 index 0000000000..58d85d1310 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "strings" + "time" +) + +// PointInTimeCreateParams represents possible parameters for the PointInTimeCreateReq +type PointInTimeCreateParams struct { + KeepAlive time.Duration + Preference string + Routing string + ExpandWildcards string + AllowPartialPitCreation bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r PointInTimeCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.KeepAlive != 0 { + params["keep_alive"] = formatDuration(r.KeepAlive) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.AllowPartialPitCreation { + params["allow_partial_pit_creation"] = "true" + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create.go new file mode 100644 index 0000000000..5903dd89ce --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-create.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// PointInTimeCreateReq represents possible options for the index create request +type PointInTimeCreateReq struct { + Indices []string + + Header http.Header + Params PointInTimeCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeCreateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_search/point_in_time") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search/point_in_time") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeCreateResp represents the returned struct of the index create response +type PointInTimeCreateResp struct { + PitID string `json:"pit_id"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + } `json:"_shards"` + CreationTime int64 `json:"creation_time"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete-params.go new file mode 100644 index 0000000000..d8a5892350 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete-params.go @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "strings" + +// PointInTimeDeleteParams represents possible parameters for the PointInTimeDeleteReq +type PointInTimeDeleteParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r PointInTimeDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete.go new file mode 100644 index 0000000000..6d6f82121d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-delete.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// PointInTimeDeleteReq represents possible options for the index create request +type PointInTimeDeleteReq struct { + PitID []string + + Header http.Header + Params PointInTimeDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeDeleteReq) GetRequest() (*http.Request, error) { + var body io.Reader + if len(r.PitID) > 0 { + bodyStruct := PointInTimeDeleteRequestBody{PitID: r.PitID} + bodyJSON, err := json.Marshal(bodyStruct) + if err != nil { + return nil, err + } + body = bytes.NewBuffer(bodyJSON) + } + + return opensearch.BuildRequest( + "DELETE", + "/_search/point_in_time", + body, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeDeleteRequestBody is used to from the delete request body +type PointInTimeDeleteRequestBody struct { + PitID []string `json:"pit_id"` +} + +// PointInTimeDeleteResp represents the returned struct of the index create response +type PointInTimeDeleteResp struct { + Pits []struct { + PitID string `json:"pit_id"` + Successful bool `json:"successful"` + } `json:"pits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get-params.go new file mode 100644 index 0000000000..c7cba9edd9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get-params.go @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "strings" + +// PointInTimeGetParams represents possible parameters for the PointInTimeGetReq +type PointInTimeGetParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r PointInTimeGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get.go new file mode 100644 index 0000000000..0fcf3982f4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time-get.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// PointInTimeGetReq represents possible options for the index create request +type PointInTimeGetReq struct { + Header http.Header + Params PointInTimeGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_search/point_in_time/_all", + nil, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeGetResp represents the returned struct of the index create response +type PointInTimeGetResp struct { + Pits []struct { + PitID string `json:"pit_id"` + CreationTime int `json:"creation_time"` + KeepAlive int64 `json:"keep_alive"` + } `json:"pits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time.go new file mode 100644 index 0000000000..bc1a80af7c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_point_in_time.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type pointInTimeClient struct { + apiClient *Client +} + +// Create executes a creade pointInTime request with the required PointInTimeCreateReq +func (c pointInTimeClient) Create(ctx context.Context, req PointInTimeCreateReq) (*PointInTimeCreateResp, error) { + var ( + data PointInTimeCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete pointInTime request with the required PointInTimeDeleteReq +func (c pointInTimeClient) Delete(ctx context.Context, req PointInTimeDeleteReq) (*PointInTimeDeleteResp, error) { + var ( + data PointInTimeDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get pointInTime request with the optional PointInTimeGetReq +func (c pointInTimeClient) Get(ctx context.Context, req *PointInTimeGetReq) (*PointInTimeGetResp, error) { + if req == nil { + req = &PointInTimeGetReq{} + } + + var ( + data PointInTimeGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval-params.go new file mode 100644 index 0000000000..06fb978aac --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// RankEvalParams represents possible parameters for the RankEvalReq +type RankEvalParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + SearchType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r RankEvalParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval.go new file mode 100644 index 0000000000..1aa1bc3027 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_rank_eval.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// RankEval executes a /_rank_eval request with the required RankEvalReq +func (c Client) RankEval(ctx context.Context, req RankEvalReq) (*RankEvalResp, error) { + var ( + data RankEvalResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// RankEvalReq represents possible options for the /_rank_eval request +type RankEvalReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params RankEvalParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r RankEvalReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_rank_eval") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_rank_eval") + return opensearch.BuildRequest( + "GET", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// RankEvalResp represents the returned struct of the /_rank_eval response +type RankEvalResp struct { + MetricScore float64 `json:"metric_score"` + Details json.RawMessage `json:"details"` + Failures json.RawMessage `json:"failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r RankEvalResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex-params.go new file mode 100644 index 0000000000..9a1c619727 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex-params.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// ReindexParams represents possible parameters for the ReindexReq +type ReindexParams struct { + MaxDocs *int + Refresh *bool + RequestsPerSecond *int + Scroll time.Duration + Slices interface{} + Timeout time.Duration + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ReindexParams) get() map[string]string { + params := make(map[string]string) + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex.go new file mode 100644 index 0000000000..05034e0bec --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Reindex executes a / request with the optional ReindexReq +func (c Client) Reindex(ctx context.Context, req ReindexReq) (*ReindexResp, error) { + var ( + data ReindexResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ReindexReq represents possible options for the / request +type ReindexReq struct { + Body io.Reader + + Header http.Header + Params ReindexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ReindexReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_reindex", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ReindexResp represents the returned struct of the / response +type ReindexResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` + Task string `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ReindexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle-params.go new file mode 100644 index 0000000000..a77dc2b1cb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// ReindexRethrottleParams represents possible parameters for the ReindexRethrottleReq +type ReindexRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ReindexRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle.go new file mode 100644 index 0000000000..ec123ab9a5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_reindex_rethrottle.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ReindexRethrottle executes a / request with the optional ReindexRethrottleReq +func (c Client) ReindexRethrottle(ctx context.Context, req ReindexRethrottleReq) (*ReindexRethrottleResp, error) { + var ( + data ReindexRethrottleResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ReindexRethrottleReq represents possible options for the / request +type ReindexRethrottleReq struct { + TaskID string + + Header http.Header + Params ReindexRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ReindexRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_reindex/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ReindexRethrottleResp represents the returned struct of the / response +type ReindexRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + NodeFailures []FailuresCause `json:"node_failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ReindexRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template-params.go new file mode 100644 index 0000000000..96ec116d64 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// RenderSearchTemplateParams represents possible parameters for the RenderSearchTemplateReq +type RenderSearchTemplateParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r RenderSearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template.go new file mode 100644 index 0000000000..b419221fb5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_render_search_template.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// RenderSearchTemplate executes a /_render/template request with the required RenderSearchTemplateReq +func (c Client) RenderSearchTemplate(ctx context.Context, req RenderSearchTemplateReq) (*RenderSearchTemplateResp, error) { + var ( + data RenderSearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// RenderSearchTemplateReq represents possible options for the /_render/template request +type RenderSearchTemplateReq struct { + TemplateID string + + Body io.Reader + + Header http.Header + Params RenderSearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r RenderSearchTemplateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_render/template") + len(r.TemplateID)) + path.WriteString("/_render/template") + if len(r.TemplateID) > 0 { + path.WriteString("/") + path.WriteString(r.TemplateID) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// RenderSearchTemplateResp represents the returned struct of the /_render/template response +type RenderSearchTemplateResp struct { + TemplateOutput json.RawMessage `json:"template_output"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r RenderSearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context-params.go new file mode 100644 index 0000000000..63f7956647 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ScriptContextParams represents possible parameters for the ScriptContextReq +type ScriptContextParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptContextParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context.go new file mode 100644 index 0000000000..1e42f69fa9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-context.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptContextReq represents possible options for the delete script request +type ScriptContextReq struct { + Header http.Header + Params ScriptContextParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptContextReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_script_context", + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptContextResp represents the returned struct of the delete script response +type ScriptContextResp struct { + Contexts []struct { + Name string `json:"name"` + Methods []struct { + Name string `json:"name"` + ReturnType string `json:"return_type"` + Params []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"params"` + } `json:"methods"` + } `json:"contexts"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptContextResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete-params.go new file mode 100644 index 0000000000..5e1e15e44c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// ScriptDeleteParams represents possible parameters for the ScriptDeleteReq +type ScriptDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete.go new file mode 100644 index 0000000000..3d033955c2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptDeleteReq represents possible options for the delete script request +type ScriptDeleteReq struct { + ScriptID string + + Header http.Header + Params ScriptDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_scripts/%s", r.ScriptID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptDeleteResp represents the returned struct of the delete script response +type ScriptDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get-params.go new file mode 100644 index 0000000000..996041f8d3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// ScriptGetParams represents possible parameters for the ScriptGetReq +type ScriptGetParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptGetParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get.go new file mode 100644 index 0000000000..fb2948ccbd --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-get.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptGetReq represents possible options for the get script request +type ScriptGetReq struct { + ScriptID string + + Header http.Header + Params ScriptGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_scripts/%s", r.ScriptID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptGetResp represents the returned struct of the get script response +type ScriptGetResp struct { + ID string `json:"_id"` + Found bool `json:"found"` + Script struct { + Lang string `json:"lang"` + Source string `json:"source"` + } `json:"script"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language-params.go new file mode 100644 index 0000000000..6a5a729b0a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ScriptLanguageParams represents possible parameters for the ScriptLanguageReq +type ScriptLanguageParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptLanguageParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language.go new file mode 100644 index 0000000000..26cf2eb14a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-language.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptLanguageReq represents possible options for the delete script request +type ScriptLanguageReq struct { + Header http.Header + Params ScriptLanguageParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptLanguageReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_script_language", + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptLanguageResp represents the returned struct of the delete script response +type ScriptLanguageResp struct { + TypesAllowed []string `json:"types_allowed"` + LanguageContexts []struct { + Language string `json:"language"` + Contexts []string `json:"contexts"` + } `json:"language_contexts"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptLanguageResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute-params.go new file mode 100644 index 0000000000..f5bd647402 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ScriptPainlessExecuteParams represents possible parameters for the ScriptPainlessExecuteReq +type ScriptPainlessExecuteParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptPainlessExecuteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute.go new file mode 100644 index 0000000000..21c63d8070 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-painless_execute.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptPainlessExecuteReq represents possible options for the delete script request +type ScriptPainlessExecuteReq struct { + Body io.Reader + + Header http.Header + Params ScriptPainlessExecuteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptPainlessExecuteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_scripts/painless/_execute", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScriptPainlessExecuteResp represents the returned struct of the delete script response +type ScriptPainlessExecuteResp struct { + Result json.RawMessage `json:"result"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptPainlessExecuteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put-params.go new file mode 100644 index 0000000000..ad196f0001 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// ScriptPutParams represents possible parameters for the ScriptPutReq +type ScriptPutParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScriptPutParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put.go new file mode 100644 index 0000000000..6af90dc664 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script-put.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScriptPutReq represents possible options for the put script request +type ScriptPutReq struct { + ScriptID string + ScriptContext string + + Body io.Reader + + Header http.Header + Params ScriptPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptPutReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_scripts//") + len(r.ScriptID) + len(r.ScriptContext)) + path.WriteString("/_scripts/") + path.WriteString(r.ScriptID) + if r.ScriptContext != "" { + path.WriteString("/") + path.WriteString(r.ScriptContext) + } + + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScriptPutResp represents the returned struct of the put script response +type ScriptPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script.go new file mode 100644 index 0000000000..2e3e0b60f5 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_script.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type scriptClient struct { + apiClient *Client +} + +// Delete executes a delete script request with the required ScriptDeleteReq +func (c scriptClient) Delete(ctx context.Context, req ScriptDeleteReq) (*ScriptDeleteResp, error) { + var ( + data ScriptDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes an put script request with the required ScriptPutReq +func (c scriptClient) Put(ctx context.Context, req ScriptPutReq) (*ScriptPutResp, error) { + var ( + data ScriptPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a /_script request with the required ScriptGetReq +func (c scriptClient) Get(ctx context.Context, req ScriptGetReq) (*ScriptGetResp, error) { + var ( + data ScriptGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Context executes a /_script_context request with the optional ScriptContextReq +func (c scriptClient) Context(ctx context.Context, req *ScriptContextReq) (*ScriptContextResp, error) { + if req == nil { + req = &ScriptContextReq{} + } + + var ( + data ScriptContextResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Language executes a /_script_context request with the optional ScriptLanguageReq +func (c scriptClient) Language(ctx context.Context, req *ScriptLanguageReq) (*ScriptLanguageResp, error) { + if req == nil { + req = &ScriptLanguageReq{} + } + + var ( + data ScriptLanguageResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PainlessExecute executes a /_script request with the required ScriptPainlessExecuteReq +func (c scriptClient) PainlessExecute(ctx context.Context, req ScriptPainlessExecuteReq) (*ScriptPainlessExecuteResp, error) { + var ( + data ScriptPainlessExecuteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete-params.go new file mode 100644 index 0000000000..fc02c456cc --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete-params.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strings" + +// ScrollDeleteParams represents possible parameters for the ScrollDeleteReq +type ScrollDeleteParams struct { + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScrollDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete.go new file mode 100644 index 0000000000..62817053d4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-delete.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScrollDeleteReq represents possible options for the index create request +type ScrollDeleteReq struct { + ScrollIDs []string + + Body io.Reader + + Header http.Header + Params ScrollDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScrollDeleteReq) GetRequest() (*http.Request, error) { + scrolls := strings.Join(r.ScrollIDs, ",") + var path strings.Builder + path.Grow(len("/_search/scroll/") + len(scrolls)) + path.WriteString("/_search/scroll") + if len(r.ScrollIDs) > 0 { + path.WriteString("/") + path.WriteString(scrolls) + } + return opensearch.BuildRequest( + "DELETE", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScrollDeleteResp represents the returned struct of the index create response +type ScrollDeleteResp struct { + NumFreed int `json:"num_freed"` + Succeeded bool `json:"succeeded"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScrollDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get-params.go new file mode 100644 index 0000000000..345dfb4bb7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ScrollGetParams represents possible parameters for the ScrollGetReq +type ScrollGetParams struct { + RestTotalHitsAsInt *bool + Scroll time.Duration + ScrollID string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r ScrollGetParams) get() map[string]string { + params := make(map[string]string) + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollID != "" { + params["scroll_id"] = r.ScrollID + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get.go new file mode 100644 index 0000000000..5a6ee7be43 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll-get.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// ScrollGetReq represents possible options for the index create request +type ScrollGetReq struct { + ScrollID string + + Header http.Header + Params ScrollGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScrollGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_search/scroll", + strings.NewReader(fmt.Sprintf(`{"scroll_id":"%s"}`, r.ScrollID)), + r.Params.get(), + r.Header, + ) +} + +// ScrollGetResp represents the returned struct of the index create response +type ScrollGetResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + ScrollID *string `json:"_scroll_id,omitempty"` + TerminatedEarly bool `json:"terminated_early"` + MaxScore *float32 `json:"max_score"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScrollGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll.go new file mode 100644 index 0000000000..f8c4ef17cf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_scroll.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type scrollClient struct { + apiClient *Client +} + +// Delete executes a delete scroll request with the required ScrollDeleteReq +func (c scrollClient) Delete(ctx context.Context, req ScrollDeleteReq) (*ScrollDeleteResp, error) { + var ( + data ScrollDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get scroll request with the required ScrollGetReq +func (c scrollClient) Get(ctx context.Context, req ScrollGetReq) (*ScrollGetResp, error) { + var ( + data ScrollGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-params.go new file mode 100644 index 0000000000..a87434ec25 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-params.go @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// SearchParams represents possible parameters for the SearchReq +type SearchParams struct { + AllowNoIndices *bool + AllowPartialSearchResults *bool + Analyzer string + AnalyzeWildcard *bool + BatchedReduceSize *int + CcsMinimizeRoundtrips *bool + DefaultOperator string + Df string + DocvalueFields []string + ExpandWildcards string + Explain *bool + From *int + IgnoreThrottled *bool + IgnoreUnavailable *bool + Lenient *bool + MaxConcurrentShardRequests *int + MinCompatibleShardNode string + Preference string + PreFilterShardSize *int + Query string + RequestCache *bool + RestTotalHitsAsInt *bool + Routing []string + Scroll time.Duration + SearchPipeline string + SearchType string + SeqNoPrimaryTerm *bool + Size *int + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + StoredFields []string + SuggestField string + SuggestMode string + SuggestSize *int + SuggestText string + TerminateAfter *int + Timeout time.Duration + TrackScores *bool + TrackTotalHits interface{} + TypedKeys *bool + Version *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SearchParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.AllowPartialSearchResults != nil { + params["allow_partial_search_results"] = strconv.FormatBool(*r.AllowPartialSearchResults) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.BatchedReduceSize != nil { + params["batched_reduce_size"] = strconv.FormatInt(int64(*r.BatchedReduceSize), 10) + } + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if len(r.DocvalueFields) > 0 { + params["docvalue_fields"] = strings.Join(r.DocvalueFields, ",") + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxConcurrentShardRequests != nil { + params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) + } + + if r.MinCompatibleShardNode != "" { + params["min_compatible_shard_node"] = r.MinCompatibleShardNode + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.PreFilterShardSize != nil { + params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.SearchPipeline != "" { + params["search_pipeline"] = r.SearchPipeline + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.SeqNoPrimaryTerm != nil { + params["seq_no_primary_term"] = strconv.FormatBool(*r.SeqNoPrimaryTerm) + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.SuggestField != "" { + params["suggest_field"] = r.SuggestField + } + + if r.SuggestMode != "" { + params["suggest_mode"] = r.SuggestMode + } + + if r.SuggestSize != nil { + params["suggest_size"] = strconv.FormatInt(int64(*r.SuggestSize), 10) + } + + if r.SuggestText != "" { + params["suggest_text"] = r.SuggestText + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.TrackScores != nil { + params["track_scores"] = strconv.FormatBool(*r.TrackScores) + } + + if r.TrackTotalHits != nil { + params["track_total_hits"] = fmt.Sprintf("%v", r.TrackTotalHits) + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template-params.go new file mode 100644 index 0000000000..f53cd23f61 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template-params.go @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SearchTemplateParams represents possible parameters for the SearchTemplateReq +type SearchTemplateParams struct { + AllowNoIndices *bool + CcsMinimizeRoundtrips *bool + ExpandWildcards string + Explain *bool + IgnoreThrottled *bool + IgnoreUnavailable *bool + Preference string + Profile *bool + RestTotalHitsAsInt *bool + Routing []string + Scroll time.Duration + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Profile != nil { + params["profile"] = strconv.FormatBool(*r.Profile) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template.go new file mode 100644 index 0000000000..b79d9db27c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search-template.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SearchTemplate executes a /_search request with the optional SearchTemplateReq +func (c Client) SearchTemplate(ctx context.Context, req SearchTemplateReq) (*SearchTemplateResp, error) { + var ( + data SearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchTemplateReq represents possible options for the /_search request +type SearchTemplateReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params SearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchTemplateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_search/template") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search/template") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SearchTemplateResp represents the returned struct of the /_search response +type SearchTemplateResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Status int `json:"status"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore *float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search.go new file mode 100644 index 0000000000..fb0b27d77e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search.go @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Search executes a /_search request with the optional SearchReq +func (c Client) Search(ctx context.Context, req *SearchReq) (*SearchResp, error) { + if req == nil { + req = &SearchReq{} + } + + var ( + data SearchResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchReq represents possible options for the /_search request +type SearchReq struct { + Indices []string + Body io.Reader + + Header http.Header + Params SearchParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchReq) GetRequest() (*http.Request, error) { + var path string + if len(r.Indices) > 0 { + path = fmt.Sprintf("/%s/_search", strings.Join(r.Indices, ",")) + } else { + path = "/_search" + } + + return opensearch.BuildRequest( + "POST", + path, + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SearchResp represents the returned struct of the /_search response +type SearchResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits SearchHits `json:"hits"` + Errors bool `json:"errors"` + Aggregations json.RawMessage `json:"aggregations"` + ScrollID *string `json:"_scroll_id,omitempty"` + Suggest map[string][]Suggest `json:"suggest,omitempty"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Response +func (r SearchResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SearchHits is a list of SearchHit with Total and MaxScore fields +type SearchHits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` +} + +// SearchHit is a sub type of SearchResp containing information of the search hit with an unparsed Source field +type SearchHit struct { + Index string `json:"_index"` + ID string `json:"_id"` + Routing string `json:"_routing"` + Score float32 `json:"_score"` + Source json.RawMessage `json:"_source"` + Fields json.RawMessage `json:"fields"` + InnerHits map[string]struct { + Hits SearchHits `json:"hits"` + } `json:"inner_hits"` + Type string `json:"_type"` // Deprecated field + Sort []any `json:"sort"` + Explanation *DocumentExplainDetails `json:"_explanation"` + SeqNo *int `json:"_seq_no"` + PrimaryTerm *int `json:"_primary_term"` + Highlight map[string][]string `json:"highlight"` + MatchedQueries []string `json:"matched_queries"` +} + +// Suggest is a sub type of SearchResp containing information of the suggest field +type Suggest struct { + Text string `json:"text"` + Offset int `json:"offset"` + Length int `json:"length"` + Options []struct { + Text string `json:"text"` + Score float32 `json:"score"` + Freq int `json:"freq"` + Highlighted string `json:"highlighted"` + CollateMatch bool `json:"collate_match"` + } `json:"options"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards-params.go new file mode 100644 index 0000000000..3935c7758c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// SearchShardsParams represents possible parameters for the SearchShardsReq +type SearchShardsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + Preference string + Routing string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SearchShardsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards.go new file mode 100644 index 0000000000..28c2c80219 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_search_shards.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SearchShards executes a /_search request with the optional SearchShardsReq +func (c Client) SearchShards(ctx context.Context, req *SearchShardsReq) (*SearchShardsResp, error) { + if req == nil { + req = &SearchShardsReq{} + } + + var ( + data SearchShardsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchShardsReq represents possible options for the /_search request +type SearchShardsReq struct { + Indices []string + + Header http.Header + Params SearchShardsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchShardsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_search_shards") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search_shards") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SearchShardsResp represents the returned struct of the /_search response +type SearchShardsResp struct { + Nodes map[string]struct { + Name string `json:"name"` + EphemeralID string `json:"ephemeral_id"` + TransportAddress string `json:"transport_address"` + Attributes map[string]string `json:"attributes"` + } `json:"nodes"` + Indices map[string]json.RawMessage `json:"indices"` + Shards [][]struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node string `json:"node"` + RelocatingNode *string `json:"relocating_node"` + Shard int `json:"shard"` + Index string `json:"index"` + ExpectedShardSizeInBytes int `json:"expected_shard_size_in_bytes"` + RecoverySource struct { + Type string `json:"type"` + } `json:"recovery_source"` + UnassignedInfo struct { + Reason string `json:"reason"` + At string `json:"at"` + Delayed bool `json:"delayed"` + AllocationStatus string `json:"allocation_status"` + } `json:"unassigned_info"` + AllocationID struct { + ID string `json:"id"` + } `json:"allocation_id"` + } `json:"shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SearchShardsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone-params.go new file mode 100644 index 0000000000..adf8850269 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// SnapshotCloneParams represents possible parameters for the SnapshotCloneReq +type SnapshotCloneParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotCloneParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone.go new file mode 100644 index 0000000000..c12a6ccc27 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-clone.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotCloneReq represents possible options for the index create request +type SnapshotCloneReq struct { + Repo string + Snapshot string + TargetSnapshot string + + Body io.Reader + + Header http.Header + Params SnapshotCloneParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotCloneReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s/%s/_clone/%s", r.Repo, r.Snapshot, r.TargetSnapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotCloneResp represents the returned struct of the index create response +type SnapshotCloneResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotCloneResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create-params.go new file mode 100644 index 0000000000..d42f6decdf --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotCreateParams represents possible parameters for the SnapshotCreateReq +type SnapshotCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create.go new file mode 100644 index 0000000000..986b2c2f15 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-create.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotCreateReq represents possible options for the index create request +type SnapshotCreateReq struct { + Repo string + Snapshot string + + Body io.Reader + + Header http.Header + Params SnapshotCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, r.Snapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotCreateResp represents the returned struct of the index create response +type SnapshotCreateResp struct { + Accepted bool `json:"accepted"` + Snapshot struct { + Snapshot string `json:"snapshot"` + UUID string `json:"uuid"` + VersionID int `json:"version_id"` + Version string `json:"version"` + RemoteStoreIndexShallowCopy bool `json:"remote_store_index_shallow_copy"` + Indices []string `json:"indices"` + DataStreams []json.RawMessage `json:"data_streams"` + IncludeGlobalState bool `json:"include_global_state"` + Metadata map[string]string `json:"metadata"` + State string `json:"state"` + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + EndTime string `json:"end_time"` + EndTimeInMillis int64 `json:"end_time_in_millis"` + DurationInMillis int `json:"duration_in_millis"` + Failures []json.RawMessage `json:"failures"` + Shards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` + } `json:"shards"` + } `json:"snapshot"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete-params.go new file mode 100644 index 0000000000..e27c64bd3d --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// SnapshotDeleteParams represents possible parameters for the SnapshotDeleteReq +type SnapshotDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete.go new file mode 100644 index 0000000000..2f13553aa1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-delete.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotDeleteReq represents possible options for the index create request +type SnapshotDeleteReq struct { + Repo string + Snapshots []string + + Header http.Header + Params SnapshotDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, strings.Join(r.Snapshots, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotDeleteResp represents the returned struct of the index create response +type SnapshotDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get-params.go new file mode 100644 index 0000000000..ed6c8a791b --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotGetParams represents possible parameters for the SnapshotGetReq +type SnapshotGetParams struct { + IgnoreUnavailable *bool + IncludeRepository *bool + IndexDetails *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotGetParams) get() map[string]string { + params := make(map[string]string) + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeRepository != nil { + params["include_repository"] = strconv.FormatBool(*r.IncludeRepository) + } + + if r.IndexDetails != nil { + params["index_details"] = strconv.FormatBool(*r.IndexDetails) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get.go new file mode 100644 index 0000000000..33925c555e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-get.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotGetReq represents possible options for the index create request +type SnapshotGetReq struct { + Repo string + Snapshots []string + + Body io.Reader + + Header http.Header + Params SnapshotGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, strings.Join(r.Snapshots, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotGetResp represents the returned struct of the index create response +type SnapshotGetResp struct { + Snapshots []SnapshotGet `json:"snapshots"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SnapshotGet is a sub type of SnapshotGetResp represeting a single snapshot +type SnapshotGet struct { + Snapshot string `json:"snapshot"` + UUID string `json:"uuid"` + VersionID int `json:"version_id"` + Version string `json:"version"` + RemoteStoreIndexShallowCopy bool `json:"remote_store_index_shallow_copy"` + Indices []string `json:"indices"` + DataStreams []json.RawMessage `json:"data_streams"` + IncludeGlobalState bool `json:"include_global_state"` + Metadata map[string]string `json:"metadata"` + State string `json:"state"` + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + EndTime string `json:"end_time"` + EndTimeInMillis int64 `json:"end_time_in_millis"` + DurationInMillis int `json:"duration_in_millis"` + Failures []json.RawMessage `json:"failures"` + Shards SnapshotGetShards `json:"shards"` +} + +// SnapshotGetShards is a sub type of SnapshotGet containing shard numbers +type SnapshotGetShards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore-params.go new file mode 100644 index 0000000000..8db2537f56 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotRestoreParams represents possible parameters for the SnapshotRestoreReq +type SnapshotRestoreParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRestoreParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore.go new file mode 100644 index 0000000000..2264e43659 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-restore.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRestoreReq represents possible options for the index create request +type SnapshotRestoreReq struct { + Repo string + Snapshot string + + Body io.Reader + + Header http.Header + Params SnapshotRestoreParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRestoreReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/%s/_restore", r.Repo, r.Snapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRestoreResp represents the returned struct of the index create response +type SnapshotRestoreResp struct { + Accepted bool `json:"accepted"` + Snapshot struct { + Snapshot string `json:"snapshot"` + Indices []string `json:"indices"` + Shards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` + } `json:"shards"` + } `json:"snapshot"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRestoreResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status-params.go new file mode 100644 index 0000000000..c3aecb213a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotStatusParams represents possible parameters for the SnapshotStatusReq +type SnapshotStatusParams struct { + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotStatusParams) get() map[string]string { + params := make(map[string]string) + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status.go new file mode 100644 index 0000000000..e63caeba0e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot-status.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotStatusReq represents possible options for the index create request +type SnapshotStatusReq struct { + Repo string + Snapshots []string + + Header http.Header + Params SnapshotStatusParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotStatusReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_snapshot/%s/%s/_status", r.Repo, strings.Join(r.Snapshots, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotStatusResp represents the returned struct of the index create response +type SnapshotStatusResp struct { + Accepted bool `json:"accepted"` + Snapshots []struct { + Snapshot string `json:"snapshot"` + Repository string `json:"repository"` + UUID string `json:"uuid"` + State string `json:"state"` + IncludeGlobalState bool `json:"include_global_state"` + ShardsStats SnapshotStatusShardsStats `json:"shards_stats"` + Stats SnapshotStatusStats `json:"stats"` + Indices map[string]struct { + ShardsStats SnapshotStatusShardsStats `json:"shards_stats"` + Stats SnapshotStatusStats `json:"stats"` + Shards map[string]struct { + Stage string `json:"stage"` + Stats SnapshotStatusStats `json:"stats"` + } `json:"shards"` + } `json:"indices"` + } `json:"snapshots"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotStatusResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SnapshotStatusShardsStats is a sub type of SnapshotStatusResp containing information about shard stats +type SnapshotStatusShardsStats struct { + Initializing int `json:"initializing"` + Started int `json:"started"` + Finalizing int `json:"finalizing"` + Done int `json:"done"` + Failed int `json:"failed"` + Total int `json:"total"` +} + +// SnapshotStatusStats is a sub type of SnapshotStatusResp containing information about snapshot stats +type SnapshotStatusStats struct { + Incremental struct { + FileCount int `json:"file_count"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"incremental"` + Total struct { + FileCount int `json:"file_count"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"total"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + TimeInMillis int `json:"time_in_millis"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot.go new file mode 100644 index 0000000000..9fa7548283 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "context" + +type snapshotClient struct { + apiClient *Client + Repository repositoryClient +} + +// Create executes a creade snapshot request with the required SnapshotCreateReq +func (c snapshotClient) Create(ctx context.Context, req SnapshotCreateReq) (*SnapshotCreateResp, error) { + var ( + data SnapshotCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete snapshot request with the required SnapshotDeleteReq +func (c snapshotClient) Delete(ctx context.Context, req SnapshotDeleteReq) (*SnapshotDeleteResp, error) { + var ( + data SnapshotDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get snapshot request with the required SnapshotGetReq +func (c snapshotClient) Get(ctx context.Context, req SnapshotGetReq) (*SnapshotGetResp, error) { + var ( + data SnapshotGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Clone executes a snapshot clone request with the required SnapshotCloneReq +func (c snapshotClient) Clone(ctx context.Context, req SnapshotCloneReq) (*SnapshotCloneResp, error) { + var ( + data SnapshotCloneResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Restore executes a snapshot restore request with the required SnapshotRestoreReq +func (c snapshotClient) Restore(ctx context.Context, req SnapshotRestoreReq) (*SnapshotRestoreResp, error) { + var ( + data SnapshotRestoreResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Status executes a snapshot status request with the required SnapshotStatusReq +func (c snapshotClient) Status(ctx context.Context, req SnapshotStatusReq) (*SnapshotStatusResp, error) { + var ( + data SnapshotStatusResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup-params.go new file mode 100644 index 0000000000..e9c89aa003 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// SnapshotRepositoryCleanupParams represents possible parameters for the SnapshotRepositoryCleanupReq +type SnapshotRepositoryCleanupParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRepositoryCleanupParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup.go new file mode 100644 index 0000000000..072a9ca59f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-cleanup.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRepositoryCleanupReq represents possible options for the index create request +type SnapshotRepositoryCleanupReq struct { + Repo string + + Header http.Header + Params SnapshotRepositoryCleanupParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryCleanupReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/_cleanup", r.Repo), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryCleanupResp represents the returned struct of the index create response +type SnapshotRepositoryCleanupResp struct { + Results struct { + DeletedBytes int `json:"deleted_bytes"` + DeletedBlobs int `json:"deleted_blobs"` + } `json:"results"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryCleanupResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create-params.go new file mode 100644 index 0000000000..8621879910 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotRepositoryCreateParams represents possible parameters for the SnapshotRepositoryCreateReq +type SnapshotRepositoryCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + Verify *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRepositoryCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Verify != nil { + params["verify"] = strconv.FormatBool(*r.Verify) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create.go new file mode 100644 index 0000000000..ba01e11615 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRepositoryCreateReq represents possible options for the index create request +type SnapshotRepositoryCreateReq struct { + Repo string + + Body io.Reader + + Header http.Header + Params SnapshotRepositoryCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s", r.Repo), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryCreateResp represents the returned struct of the index create response +type SnapshotRepositoryCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete-params.go new file mode 100644 index 0000000000..d10ee46b0f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete-params.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// SnapshotRepositoryDeleteParams represents possible parameters for the SnapshotRepositoryDeleteReq +type SnapshotRepositoryDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRepositoryDeleteParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete.go new file mode 100644 index 0000000000..4a51de58a8 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-delete.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRepositoryDeleteReq represents possible options for the index create request +type SnapshotRepositoryDeleteReq struct { + Repos []string + + Header http.Header + Params SnapshotRepositoryDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryDeleteReq) GetRequest() (*http.Request, error) { + repos := strings.Join(r.Repos, ",") + + var path strings.Builder + path.Grow(len("/_snapshot/") + len(repos)) + path.WriteString("/_snapshot") + if len(r.Repos) > 0 { + path.WriteString("/") + path.WriteString(repos) + } + + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryDeleteResp represents the returned struct of the index create response +type SnapshotRepositoryDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get-params.go new file mode 100644 index 0000000000..388c512e2c --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get-params.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SnapshotRepositoryGetParams represents possible parameters for the SnapshotRepositoryGetReq +type SnapshotRepositoryGetParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRepositoryGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get.go new file mode 100644 index 0000000000..f042396005 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-get.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRepositoryGetReq represents possible options for the index create request +type SnapshotRepositoryGetReq struct { + Repos []string + + Header http.Header + Params SnapshotRepositoryGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryGetReq) GetRequest() (*http.Request, error) { + repos := strings.Join(r.Repos, ",") + + var path strings.Builder + path.Grow(len("/_snapshot/") + len(repos)) + path.WriteString("/_snapshot") + if len(r.Repos) > 0 { + path.WriteString("/") + path.WriteString(repos) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryGetResp represents the returned struct of the index create response +type SnapshotRepositoryGetResp struct { + Repos map[string]struct { + Type string `json:"type"` + Settings map[string]string `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify-params.go new file mode 100644 index 0000000000..768183c5e3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// SnapshotRepositoryVerifyParams represents possible parameters for the SnapshotRepositoryVerifyReq +type SnapshotRepositoryVerifyParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r SnapshotRepositoryVerifyParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify.go new file mode 100644 index 0000000000..5542af7e3a --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository-verify.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// SnapshotRepositoryVerifyReq represents possible options for the index create request +type SnapshotRepositoryVerifyReq struct { + Repo string + + Header http.Header + Params SnapshotRepositoryVerifyParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryVerifyReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/_verify", r.Repo), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryVerifyResp represents the returned struct of the index create response +type SnapshotRepositoryVerifyResp struct { + Nodes map[string]struct { + Name string `json:"name"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryVerifyResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository.go new file mode 100644 index 0000000000..9bd139a9c3 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_snapshot_repository.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type repositoryClient struct { + apiClient *Client +} + +// Create executes a put repository request with the required SnapshotRepositoryCreateReq +func (c repositoryClient) Create(ctx context.Context, req SnapshotRepositoryCreateReq) (*SnapshotRepositoryCreateResp, error) { + var ( + data SnapshotRepositoryCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete repository request with the required SnapshotRepositoryDeleteReq +func (c repositoryClient) Delete(ctx context.Context, req SnapshotRepositoryDeleteReq) (*SnapshotRepositoryDeleteResp, error) { + var ( + data SnapshotRepositoryDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get repository request with the optional SnapshotRepositoryGetReq +func (c repositoryClient) Get(ctx context.Context, req *SnapshotRepositoryGetReq) (*SnapshotRepositoryGetResp, error) { + if req == nil { + req = &SnapshotRepositoryGetReq{} + } + var ( + data SnapshotRepositoryGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Repos); err != nil { + return &data, err + } + + return &data, nil +} + +// Cleanup executes a cleanup repository request with the required SnapshotRepositoryCleanupReq +func (c repositoryClient) Cleanup(ctx context.Context, req SnapshotRepositoryCleanupReq) (*SnapshotRepositoryCleanupResp, error) { + var ( + data SnapshotRepositoryCleanupResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Verify executes a verify repository request with the required SnapshotRepositoryVerifyReq +func (c repositoryClient) Verify(ctx context.Context, req SnapshotRepositoryVerifyReq) (*SnapshotRepositoryVerifyResp, error) { + var ( + data SnapshotRepositoryVerifyResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel-params.go new file mode 100644 index 0000000000..faf1bf0a85 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// TasksCancelParams represents possible parameters for the TasksCancelReq +type TasksCancelParams struct { + Actions []string + Nodes []string + ParentTaskID string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TasksCancelParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel.go new file mode 100644 index 0000000000..4c3d0596ba --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-cancel.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TasksCancelReq represents possible options for the index create request +type TasksCancelReq struct { + TaskID string + + Header http.Header + Params TasksCancelParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksCancelReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_tasks//_cancel") + len(r.TaskID)) + path.WriteString("/_tasks") + if r.TaskID != "" { + path.WriteString("/") + path.WriteString(r.TaskID) + } + path.WriteString("/_cancel") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksCancelResp represents the returned struct of the index create response +type TasksCancelResp struct { + Nodes map[string]TaskCancel `json:"nodes"` + NodeFailures []FailuresCause `json:"node_failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksCancelResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TaskCancel is a sub type of TaskCancelResp containing information about a node the task was running on +type TaskCancel struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]TaskCancelInfo `json:"tasks"` +} + +// TaskCancelInfo is a sub type of TaskCancle containing information about the canceled task +type TaskCancelInfo struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + CancellationTimeMillis int64 `json:"cancellation_time_millis"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get-params.go new file mode 100644 index 0000000000..72f75a5303 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get-params.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TasksGetParams represents possible parameters for the TasksGetReq +type TasksGetParams struct { + Timeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TasksGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get.go new file mode 100644 index 0000000000..45411fac61 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-get.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TasksGetReq represents possible options for the index create request +type TasksGetReq struct { + TaskID string + + Header http.Header + Params TasksGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_tasks/%s", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksGetResp represents the returned struct of the index create response +type TasksGetResp struct { + Completed bool `json:"completed"` + Task struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int64 `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TasksGetDetails is a sub type of TasksGetResp containing information about an index template +type TasksGetDetails struct { + Order int64 `json:"order"` + Version int64 `json:"version"` + IndexPatterns []string `json:"index_patterns"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list-params.go new file mode 100644 index 0000000000..f691b8d1d2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TasksListParams represents possible parameters for the TasksListReq +type TasksListParams struct { + Actions []string + Detailed *bool + GroupBy string + Nodes []string + ParentTaskID string + Timeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TasksListParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if r.GroupBy != "" { + params["group_by"] = r.GroupBy + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list.go new file mode 100644 index 0000000000..0332f851fb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks-list.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TasksListReq represents possible options for the index create request +type TasksListReq struct { + Header http.Header + Params TasksListParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksListReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksListResp represents the returned struct of the index create response +type TasksListResp struct { + Nodes map[string]TasksListNodes `json:"nodes"` + Tasks map[string]TasksListTask `json:"tasks"` // tasks is returned when group_by is set to none or parents + NodeFailures []FailuresCause `json:"node_failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksListResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TasksListNodes is a sub type of TaskListResp containing information about a node and the tasks running on it +type TasksListNodes struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]TasksListTask `json:"tasks"` +} + +// TasksListTask is a sub type of TaskListResp, TaskListNodes containing information about a task +type TasksListTask struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int64 `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers map[string]string `json:"headers"` + ResourceStats TasksListResourceStats `json:"resource_stats"` + ParentTaskID string `json:"parent_task_id"` + Children []TasksListTask `json:"children,omitempty"` +} + +// TasksListResourceStats is a sub type of TaskListTask containing information about task stats +type TasksListResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks.go new file mode 100644 index 0000000000..bd31696f92 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_tasks.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type tasksClient struct { + apiClient *Client +} + +// Cancel executes a delete tasks request with the required TasksCancelReq +func (c tasksClient) Cancel(ctx context.Context, req TasksCancelReq) (*TasksCancelResp, error) { + var ( + data TasksCancelResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// List executes a get tasks request with the optional TasksListReq +func (c tasksClient) List(ctx context.Context, req *TasksListReq) (*TasksListResp, error) { + if req == nil { + req = &TasksListReq{} + } + + var ( + data TasksListResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get tasks request with the optional TasksGetReq +func (c tasksClient) Get(ctx context.Context, req TasksGetReq) (*TasksGetResp, error) { + var ( + data TasksGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create-params.go new file mode 100644 index 0000000000..51a1c89bcb --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TemplateCreateParams represents possible parameters for the TemplateCreateReq +type TemplateCreateParams struct { + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Order *int + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Order != nil { + params["order"] = strconv.FormatInt(int64(*r.Order), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create.go new file mode 100644 index 0000000000..fa974f0bc9 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TemplateCreateReq represents possible options for the index create request +type TemplateCreateReq struct { + Template string + + Body io.Reader + + Header http.Header + Params TemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_template/%s", r.Template), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// TemplateCreateResp represents the returned struct of the index create response +type TemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete-params.go new file mode 100644 index 0000000000..401b764324 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strings" + "time" +) + +// TemplateDeleteParams represents possible parameters for the TemplateDeleteReq +type TemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete.go new file mode 100644 index 0000000000..5bc7f0b6d4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TemplateDeleteReq represents possible options for the index create request +type TemplateDeleteReq struct { + Template string + + Header http.Header + Params TemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_template/%s", r.Template), + nil, + r.Params.get(), + r.Header, + ) +} + +// TemplateDeleteResp represents the returned struct of the index create response +type TemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists-params.go new file mode 100644 index 0000000000..b6bc8d0655 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TemplateExistsParams represents possible parameters for the TemplateExistsReq +type TemplateExistsParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists.go new file mode 100644 index 0000000000..a740618185 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TemplateExistsReq represents possible options for the index create request +type TemplateExistsReq struct { + Template string + + Header http.Header + Params TemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_template/%s", r.Template), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get-params.go new file mode 100644 index 0000000000..55aec6c443 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get-params.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TemplateGetParams represents possible parameters for the TemplateGetReq +type TemplateGetParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get.go new file mode 100644 index 0000000000..95b2d66a58 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template-get.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// TemplateGetReq represents possible options for the index create request +type TemplateGetReq struct { + Templates []string + + Header http.Header + Params TemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_template/%s", strings.Join(r.Templates, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// TemplateGetResp represents the returned struct of the index create response +type TemplateGetResp struct { + Templates map[string]TemplateGetDetails + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TemplateGetDetails is a sub type of TemplateGetResp containing information about an index template +type TemplateGetDetails struct { + Order int64 `json:"order"` + Version int64 `json:"version"` + IndexPatterns []string `json:"index_patterns"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template.go new file mode 100644 index 0000000000..be9f1b4aed --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_template.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v4" +) + +type templateClient struct { + apiClient *Client +} + +// Create executes a creade template request with the required TemplateCreateReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Create instread +func (c templateClient) Create(ctx context.Context, req TemplateCreateReq) (*TemplateCreateResp, error) { + var ( + data TemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete template request with the required TemplateDeleteReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Delete instread +func (c templateClient) Delete(ctx context.Context, req TemplateDeleteReq) (*TemplateDeleteResp, error) { + var ( + data TemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get template request with the optional TemplateGetReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Get instread +func (c templateClient) Get(ctx context.Context, req *TemplateGetReq) (*TemplateGetResp, error) { + if req == nil { + req = &TemplateGetReq{} + } + + var ( + data TemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Templates); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists template request with the required TemplatExistsReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Exists instread +func (c templateClient) Exists(ctx context.Context, req TemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors-params.go new file mode 100644 index 0000000000..3127454a78 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors-params.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// TermvectorsParams represents possible parameters for the TermvectorsReq +type TermvectorsParams struct { + Fields []string + FieldStatistics *bool + Offsets *bool + Payloads *bool + Positions *bool + Preference string + Realtime *bool + Routing string + TermStatistics *bool + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r TermvectorsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.FieldStatistics != nil { + params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) + } + + if r.Offsets != nil { + params["offsets"] = strconv.FormatBool(*r.Offsets) + } + + if r.Payloads != nil { + params["payloads"] = strconv.FormatBool(*r.Payloads) + } + + if r.Positions != nil { + params["positions"] = strconv.FormatBool(*r.Positions) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.TermStatistics != nil { + params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors.go new file mode 100644 index 0000000000..d25d4b3675 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_termvectors.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Termvectors executes a /_termvectors request with the required TermvectorsReq +func (c Client) Termvectors(ctx context.Context, req TermvectorsReq) (*TermvectorsResp, error) { + var ( + data TermvectorsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// TermvectorsReq represents possible options for the /_termvectors request +type TermvectorsReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params TermvectorsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TermvectorsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_termvectors/") + len(r.Index) + len(r.DocumentID)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_termvectors") + if len(r.DocumentID) > 0 { + path.WriteString("/") + path.WriteString(r.DocumentID) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// TermvectorsResp represents the returned struct of the /_termvectors response +type TermvectorsResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Found bool `json:"found"` + Took int `json:"took"` + Type string `json:"_type"` // Deprecated field + TermVectors json.RawMessage `json:"term_vectors"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TermvectorsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update-params.go new file mode 100644 index 0000000000..c2e0e7cd2e --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update-params.go @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// UpdateParams represents possible parameters for the UpdateReq +type UpdateParams struct { + IfPrimaryTerm *int + IfSeqNo *int + Lang string + Refresh string + RequireAlias *bool + RetryOnConflict *int + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r UpdateParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.Lang != "" { + params["lang"] = r.Lang + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.RetryOnConflict != nil { + params["retry_on_conflict"] = strconv.FormatInt(int64(*r.RetryOnConflict), 10) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if source, ok := r.Source.(bool); ok { + params["_source"] = strconv.FormatBool(source) + } else if source, ok := r.Source.(string); ok && source != "" { + params["_source"] = source + } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { + params["_source"] = strings.Join(sources, ",") + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update.go new file mode 100644 index 0000000000..54ab8e1d83 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Update executes a /_update request with the optional UpdateReq +func (c Client) Update(ctx context.Context, req UpdateReq) (*UpdateResp, error) { + var ( + data UpdateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateReq represents possible options for the /_update request +type UpdateReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params UpdateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_update/%s", r.Index, r.DocumentID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// UpdateResp represents the returned struct of the /_update response +type UpdateResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Type string `json:"_type"` // Deprecated field + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query-params.go new file mode 100644 index 0000000000..dca60556d0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query-params.go @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// UpdateByQueryParams represents possible parameters for the UpdateByQueryReq +type UpdateByQueryParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + Conflicts string + DefaultOperator string + Df string + ExpandWildcards string + From *int + IgnoreUnavailable *bool + Lenient *bool + MaxDocs *int + Pipeline string + Preference string + Query string + Refresh *bool + RequestCache *bool + RequestsPerSecond *int + Routing []string + Scroll time.Duration + ScrollSize *int + SearchTimeout time.Duration + SearchType string + Size *int + Slices interface{} + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + TerminateAfter *int + Timeout time.Duration + Version *bool + VersionType *bool + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r UpdateByQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.Conflicts != "" { + params["conflicts"] = r.Conflicts + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollSize != nil { + params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) + } + + if r.SearchTimeout != 0 { + params["search_timeout"] = formatDuration(r.SearchTimeout) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + if source, ok := r.Source.(bool); ok { + params["_source"] = strconv.FormatBool(source) + } else if source, ok := r.Source.(string); ok && source != "" { + params["_source"] = source + } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { + params["_source"] = strings.Join(sources, ",") + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.VersionType != nil { + params["version_type"] = strconv.FormatBool(*r.VersionType) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query.go new file mode 100644 index 0000000000..ff0b5b881f --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// UpdateByQuery executes a /_update_by_query request with the optional UpdateByQueryReq +func (c Client) UpdateByQuery(ctx context.Context, req UpdateByQueryReq) (*UpdateByQueryResp, error) { + var ( + data UpdateByQueryResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateByQueryReq represents possible options for the /_update_by_query request +type UpdateByQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params UpdateByQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateByQueryReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_update_by_query", strings.Join(r.Indices, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// UpdateByQueryResp represents the returned struct of the /_update_by_query response +type UpdateByQueryResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Updated int `json:"updated"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float32 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` + Type string `json:"_type"` // Deprecated field + Task string `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateByQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle-params.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle-params.go new file mode 100644 index 0000000000..2a270cc0d7 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// UpdateByQueryRethrottleParams represents possible parameters for the UpdateByQueryRethrottleReq +type UpdateByQueryRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool + FilterPath []string +} + +func (r UpdateByQueryRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + if len(r.FilterPath) > 0 { + params["filter_path"] = strings.Join(r.FilterPath, ",") + } + + return params +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle.go new file mode 100644 index 0000000000..5c72cf7b84 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/api_update_by_query_rethrottle.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// UpdateByQueryRethrottle executes a / request with the optional UpdateByQueryRethrottleReq +func (c Client) UpdateByQueryRethrottle(ctx context.Context, req UpdateByQueryRethrottleReq) (*UpdateByQueryRethrottleResp, error) { + var ( + data UpdateByQueryRethrottleResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateByQueryRethrottleReq represents possible options for the / request +type UpdateByQueryRethrottleReq struct { + TaskID string + + Header http.Header + Params UpdateByQueryRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateByQueryRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_update_by_query/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// UpdateByQueryRethrottleResp represents the returned struct of the / response +type UpdateByQueryRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + NodeFailures []FailuresCause `json:"node_failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateByQueryRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/inspect.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/inspect.go new file mode 100644 index 0000000000..47eabba1c1 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/inspect.go @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "github.com/opensearch-project/opensearch-go/v4" + +// Inspect represents the struct returned by Inspect() func, its main use is to return the opensearch.Response to the user +type Inspect struct { + Response *opensearch.Response +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/opensearchapi.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/opensearchapi.go new file mode 100644 index 0000000000..d23d5abfc2 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchapi/opensearchapi.go @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/opensearch-project/opensearch-go/v4" +) + +// Config represents the client configuration +type Config struct { + Client opensearch.Config +} + +// Client represents the opensearchapi Client summarizing all API calls +type Client struct { + Client *opensearch.Client + Cat catClient + Cluster clusterClient + Dangling danglingClient + Document documentClient + Indices indicesClient + Nodes nodesClient + Script scriptClient + ComponentTemplate componentTemplateClient + IndexTemplate indexTemplateClient + // Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate instead + Template templateClient + DataStream dataStreamClient + PointInTime pointInTimeClient + Ingest ingestClient + Tasks tasksClient + Scroll scrollClient + Snapshot snapshotClient +} + +// clientInit inits the Client with all sub clients +func clientInit(rootClient *opensearch.Client) *Client { + client := &Client{ + Client: rootClient, + } + client.Cat = catClient{apiClient: client} + client.Indices = indicesClient{ + apiClient: client, + Alias: aliasClient{apiClient: client}, + Mapping: mappingClient{apiClient: client}, + Settings: settingsClient{apiClient: client}, + } + client.Nodes = nodesClient{apiClient: client} + client.Cluster = clusterClient{apiClient: client} + client.Dangling = danglingClient{apiClient: client} + client.Script = scriptClient{apiClient: client} + client.Document = documentClient{apiClient: client} + client.ComponentTemplate = componentTemplateClient{apiClient: client} + client.IndexTemplate = indexTemplateClient{apiClient: client} + client.Template = templateClient{apiClient: client} + client.DataStream = dataStreamClient{apiClient: client} + client.PointInTime = pointInTimeClient{apiClient: client} + client.Ingest = ingestClient{apiClient: client} + client.Tasks = tasksClient{apiClient: client} + client.Scroll = scrollClient{apiClient: client} + client.Snapshot = snapshotClient{ + apiClient: client, + Repository: repositoryClient{apiClient: client}, + } + + return client +} + +// NewClient returns a opensearchapi client +func NewClient(config Config) (*Client, error) { + rootClient, err := opensearch.NewClient(config.Client) + if err != nil { + return nil, err + } + + return clientInit(rootClient), nil +} + +// NewDefaultClient returns a opensearchapi client using defaults +func NewDefaultClient() (*Client, error) { + rootClient, err := opensearch.NewClient(opensearch.Config{ + Addresses: []string{"http://localhost:9200"}, + }) + if err != nil { + return nil, err + } + + return clientInit(rootClient), nil +} + +// do calls the opensearch.Client.Do() and checks the response for openseach api errors +func (c *Client) do(ctx context.Context, req opensearch.Request, dataPointer any) (*opensearch.Response, error) { + resp, err := c.Client.Do(ctx, req, dataPointer) + if err != nil { + return nil, err + } + + if resp.IsError() { + if dataPointer != nil { + return resp, opensearch.ParseError(resp) + } else { + return resp, fmt.Errorf("status: %s", resp.Status()) + } + } + + return resp, nil +} + +// formatDuration converts duration to a string in the format +// accepted by Opensearch. +func formatDuration(d time.Duration) string { + if d < time.Millisecond { + return strconv.FormatInt(int64(d), 10) + "nanos" + } + + return strconv.FormatInt(int64(d)/int64(time.Millisecond), 10) + "ms" +} + +// ToPointer converts any value to a pointer, mainly used for request parameters +func ToPointer[V any](value V) *V { + return &value +} + +// ResponseShards is a sub type of api repsonses containing information about shards +type ResponseShards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []ResponseShardsFailure `json:"failures"` + Skipped int `json:"skipped"` +} + +// ResponseShardsFailure is a sub type of ReponseShards containing information about a failed shard +type ResponseShardsFailure struct { + Shard int `json:"shard"` + Index any `json:"index"` + Node string `json:"node"` + Reason struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"reason"` +} + +// FailuresCause contains information about failure cause +type FailuresCause struct { + Type string `json:"type"` + Reason string `json:"reason"` + NodeID string `json:"node_id"` + Cause *struct { + Type string `json:"type"` + Reason string `json:"reason"` + Cause *struct { + Type string `json:"type"` + Reason *string `json:"reason"` + } `json:"caused_by,omitempty"` + } `json:"caused_by,omitempty"` +} + +// FailuresShard contains information about shard failures +type FailuresShard struct { + Shard int `json:"shard"` + Index string `json:"index"` + Status string `json:"status"` + Reason FailuresCause `json:"reason"` +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/connection.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/connection.go new file mode 100644 index 0000000000..58e16ce021 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/connection.go @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchtransport + +import ( + "errors" + "fmt" + "math" + "net/url" + "sort" + "sync" + "time" +) + +const ( + defaultResurrectTimeoutInitial = 60 * time.Second + defaultResurrectTimeoutFactorCutoff = 5 +) + +// Selector defines the interface for selecting connections from the pool. +type Selector interface { + Select([]*Connection) (*Connection, error) +} + +// ConnectionPool defines the interface for the connection pool. +type ConnectionPool interface { + Next() (*Connection, error) // Next returns the next available connection. + OnSuccess(*Connection) // OnSuccess reports that the connection was successful. + OnFailure(*Connection) error // OnFailure reports that the connection failed. + URLs() []*url.URL // URLs returns the list of URLs of available connections. +} + +// Connection represents a connection to a node. +type Connection struct { + sync.Mutex + + URL *url.URL + IsDead bool + DeadSince time.Time + Failures int + + ID string + Name string + Roles []string + Attributes map[string]interface{} +} + +type singleConnectionPool struct { + connection *Connection + + metrics *metrics +} + +type statusConnectionPool struct { + sync.Mutex + + live []*Connection // List of live connections + dead []*Connection // List of dead connections + selector Selector + resurrectTimeoutInitial time.Duration + resurrectTimeoutFactorCutoff int + + metrics *metrics +} + +type roundRobinSelector struct { + sync.Mutex + + curr int // Index of the current connection +} + +// NewConnectionPool creates and returns a default connection pool. +func NewConnectionPool(conns []*Connection, selector Selector) ConnectionPool { + if len(conns) == 1 { + return &singleConnectionPool{connection: conns[0]} + } + + if selector == nil { + selector = &roundRobinSelector{curr: -1} + } + + return &statusConnectionPool{ + live: conns, + selector: selector, + resurrectTimeoutInitial: defaultResurrectTimeoutInitial, + resurrectTimeoutFactorCutoff: defaultResurrectTimeoutFactorCutoff, + } +} + +// Next returns the connection from pool. +func (cp *singleConnectionPool) Next() (*Connection, error) { + return cp.connection, nil +} + +// OnSuccess is a no-op for single connection pool. +func (cp *singleConnectionPool) OnSuccess(*Connection) {} + +// OnFailure is a no-op for single connection pool. +func (cp *singleConnectionPool) OnFailure(*Connection) error { return nil } + +// URLs returns the list of URLs of available connections. +func (cp *singleConnectionPool) URLs() []*url.URL { return []*url.URL{cp.connection.URL} } + +func (cp *singleConnectionPool) connections() []*Connection { return []*Connection{cp.connection} } + +// Next returns a connection from pool, or an error. +func (cp *statusConnectionPool) Next() (*Connection, error) { + cp.Lock() + defer cp.Unlock() + + // Return next live connection + if len(cp.live) > 0 { + return cp.selector.Select(cp.live) + } else if len(cp.dead) > 0 { + // No live connection is available, resurrect one of the dead ones. + c := cp.dead[len(cp.dead)-1] + cp.dead = cp.dead[:len(cp.dead)-1] + c.Lock() + defer c.Unlock() + cp.resurrect(c, false) + return c, nil + } + + return nil, errors.New("no connection available") +} + +// OnSuccess marks the connection as successful. +func (cp *statusConnectionPool) OnSuccess(c *Connection) { + c.Lock() + defer c.Unlock() + + // Short-circuit for live connection + if !c.IsDead { + return + } + + c.markAsHealthy() + + cp.Lock() + defer cp.Unlock() + cp.resurrect(c, true) +} + +// OnFailure marks the connection as failed. +func (cp *statusConnectionPool) OnFailure(c *Connection) error { + cp.Lock() + defer cp.Unlock() + + c.Lock() + + if c.IsDead { + if debugLogger != nil { + debugLogger.Logf("Already removed %s\n", c.URL) + } + c.Unlock() + + return nil + } + + if debugLogger != nil { + debugLogger.Logf("Removing %s...\n", c.URL) + } + + c.markAsDead() + cp.scheduleResurrect(c) + c.Unlock() + + // Push item to dead list and sort slice by number of failures + cp.dead = append(cp.dead, c) + sort.Slice(cp.dead, func(i, j int) bool { + c1 := cp.dead[i] + c2 := cp.dead[j] + c1.Lock() + c2.Lock() + defer c1.Unlock() + defer c2.Unlock() + + res := c1.Failures > c2.Failures + return res + }) + + // Check if connection exists in the list, return error if not. + index := -1 + + for i, conn := range cp.live { + if conn == c { + index = i + } + } + + if index < 0 { + // Does this error even get raised? Under what conditions can the connection not be in the cp.live list? + // If the connection is marked dead the function already ended + return errors.New("connection not in live list") + } + + // Remove item; https://github.com/golang/go/wiki/SliceTricks + copy(cp.live[index:], cp.live[index+1:]) + cp.live = cp.live[:len(cp.live)-1] + + return nil +} + +// URLs returns the list of URLs of available connections. +func (cp *statusConnectionPool) URLs() []*url.URL { + cp.Lock() + defer cp.Unlock() + + urls := make([]*url.URL, len(cp.live)) + for idx, c := range cp.live { + urls[idx] = c.URL + } + + return urls +} + +func (cp *statusConnectionPool) connections() []*Connection { + var conns []*Connection + conns = append(conns, cp.live...) + conns = append(conns, cp.dead...) + + return conns +} + +// resurrect adds the connection to the list of available connections. +// When removeDead is true, it also removes it from the dead list. +// The calling code is responsible for locking. +func (cp *statusConnectionPool) resurrect(c *Connection, removeDead bool) { + if debugLogger != nil { + debugLogger.Logf("Resurrecting %s\n", c.URL) + } + + c.markAsLive() + cp.live = append(cp.live, c) + + if removeDead { + index := -1 + + for i, conn := range cp.dead { + if conn == c { + index = i + } + } + + if index >= 0 { + // Remove item; https://github.com/golang/go/wiki/SliceTricks + copy(cp.dead[index:], cp.dead[index+1:]) + cp.dead = cp.dead[:len(cp.dead)-1] + } + } +} + +// scheduleResurrect schedules the connection to be resurrected. +func (cp *statusConnectionPool) scheduleResurrect(c *Connection) { + factor := math.Min(float64(c.Failures-1), float64(cp.resurrectTimeoutFactorCutoff)) + timeout := time.Duration(cp.resurrectTimeoutInitial.Seconds() * math.Exp2(factor) * float64(time.Second)) + + if debugLogger != nil { + debugLogger.Logf( + "Resurrect %s (failures=%d, factor=%1.1f, timeout=%s) in %s\n", + c.URL, + c.Failures, + factor, + timeout, + c.DeadSince.Add(timeout).Sub(time.Now().UTC()).Truncate(time.Second), + ) + } + + time.AfterFunc(timeout, func() { + cp.Lock() + defer cp.Unlock() + + c.Lock() + defer c.Unlock() + + if !c.IsDead { + if debugLogger != nil { + debugLogger.Logf("Already resurrected %s\n", c.URL) + } + return + } + + cp.resurrect(c, true) + }) +} + +// Select returns the connection in a round-robin fashion. +func (s *roundRobinSelector) Select(conns []*Connection) (*Connection, error) { + s.Lock() + defer s.Unlock() + + s.curr = (s.curr + 1) % len(conns) + return conns[s.curr], nil +} + +// markAsDead marks the connection as dead. +func (c *Connection) markAsDead() { + c.IsDead = true + if c.DeadSince.IsZero() { + c.DeadSince = time.Now().UTC() + } + c.Failures++ +} + +// markAsLive marks the connection as alive. +func (c *Connection) markAsLive() { + c.IsDead = false +} + +// markAsHealthy marks the connection as healthy. +func (c *Connection) markAsHealthy() { + c.IsDead = false + c.DeadSince = time.Time{} + c.Failures = 0 +} + +// String returns a readable connection representation. +func (c *Connection) String() string { + c.Lock() + defer c.Unlock() + return fmt.Sprintf("<%s> dead=%v failures=%d", c.URL, c.IsDead, c.Failures) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/discovery.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/discovery.go new file mode 100644 index 0000000000..2e0bbec851 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/discovery.go @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchtransport + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// Discoverable defines the interface for transports supporting node discovery. +type Discoverable interface { + DiscoverNodes() error +} + +// nodeInfo represents the information about node in a cluster. +type nodeInfo struct { + ID string + Name string + URL *url.URL + Roles []string `json:"roles"` + Attributes map[string]interface{} + HTTP struct { + PublishAddress string `json:"publish_address"` + } +} + +// DiscoverNodes reloads the client connections by fetching information from the cluster. +func (c *Client) DiscoverNodes() error { + conns := make([]*Connection, 0) + + nodes, err := c.getNodesInfo() + if err != nil { + if debugLogger != nil { + debugLogger.Logf("Error getting nodes info: %s\n", err) + } + + return fmt.Errorf("discovery: get nodes: %w", err) + } + + for _, node := range nodes { + var isClusterManagerOnlyNode bool + + if len(node.Roles) == 1 && (node.Roles[0] == "master" || node.Roles[0] == "cluster_manager") { + isClusterManagerOnlyNode = true + } + + if debugLogger != nil { + var skip string + if isClusterManagerOnlyNode { + skip = "; [SKIP]" + } + + debugLogger.Logf("Discovered node [%s]; %s; roles=%s%s\n", node.Name, node.URL, node.Roles, skip) + } + + // Skip cluster_manager only nodes + // TODO: Move logic to Selector? + if isClusterManagerOnlyNode { + continue + } + + conns = append(conns, &Connection{ + URL: node.URL, + ID: node.ID, + Name: node.Name, + Roles: node.Roles, + Attributes: node.Attributes, + }) + } + + c.Lock() + defer c.Unlock() + + if lockable, ok := c.pool.(sync.Locker); ok { + lockable.Lock() + defer lockable.Unlock() + } + + if c.poolFunc != nil { + c.pool = c.poolFunc(conns, c.selector) + } else { + // TODO: Replace only live connections, leave dead scheduled for resurrect? + c.pool = NewConnectionPool(conns, c.selector) + } + + return nil +} + +func (c *Client) getNodesInfo() ([]nodeInfo, error) { + scheme := c.urls[0].Scheme + + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, "/_nodes/http", nil) + if err != nil { + return nil, err + } + + c.Lock() + conn, err := c.pool.Next() + c.Unlock() + // TODO: If no connection is returned, fallback to original URLs + if err != nil { + return nil, err + } + + c.setReqURL(conn.URL, req) + c.setReqAuth(conn.URL, req) + c.setReqUserAgent(req) + + res, err := c.transport.RoundTrip(req) + if err != nil { + return nil, err + } + + if res.Body == nil { + return nil, fmt.Errorf("unexpected empty body") + } + defer res.Body.Close() + + if res.StatusCode > http.StatusOK { + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf("server error: %s: %w", res.Status, err) + } + return nil, fmt.Errorf("server error: %s: %s", res.Status, body) + } + + var env map[string]json.RawMessage + if err := json.NewDecoder(res.Body).Decode(&env); err != nil { + return nil, err + } + + var nodes map[string]nodeInfo + if err := json.Unmarshal(env["nodes"], &nodes); err != nil { + return nil, err + } + + out := make([]nodeInfo, len(nodes)) + idx := 0 + + for id, node := range nodes { + node.ID = id + u := c.getNodeURL(node, scheme) + node.URL = u + out[idx] = node + idx++ + } + + return out, nil +} + +func (c *Client) getNodeURL(node nodeInfo, scheme string) *url.URL { + var ( + host string + port string + err error + + addrs = strings.Split(node.HTTP.PublishAddress, "/") + ports = strings.Split(node.HTTP.PublishAddress, ":") + ) + + if len(addrs) > 1 { + host = addrs[0] + } else { + host, _, err = net.SplitHostPort(addrs[0]) + if err != nil { + host = strings.Split(addrs[0], ":")[0] + } + } + port = ports[len(ports)-1] + u := &url.URL{ + Scheme: scheme, + Host: net.JoinHostPort(host, port), + } + + return u +} + +func (c *Client) scheduleDiscoverNodes() { + //nolint:errcheck // errors are logged inside the function + go c.DiscoverNodes() + + c.Lock() + defer c.Unlock() + + if c.discoverNodesTimer != nil { + c.discoverNodesTimer.Stop() + } + + c.discoverNodesTimer = time.AfterFunc(c.discoverNodesInterval, func() { + c.scheduleDiscoverNodes() + }) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/doc.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/doc.go new file mode 100644 index 0000000000..721e27d5a6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/doc.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +/* +Package opensearchtransport provides the transport layer for the OpenSearch client. + +It is automatically included in the client provided by the github.com/opensearch-project/opensearch-go package +and is not intended for direct use: to configure the client, use the opensearch.Config struct. + +The default HTTP transport of the client is http.Transport; use the Transport option to customize it; + +The package will automatically retry requests on network-related errors, and on specific +response status codes (by default 502, 503, 504). Use the RetryOnStatus option to customize the list. +The transport will not retry a timeout network error, unless enabled by setting EnableRetryOnTimeout to true. + +Use the MaxRetries option to configure the number of retries, and set DisableRetry to true +to disable the retry behavior altogether. + +By default, the retry will be performed without any delay; to configure a backoff interval, +implement the RetryBackoff option function; see an example in the package unit tests for information. + +When multiple addresses are passed in configuration, the package will use them in a round-robin fashion, +and will keep track of live and dead nodes. The status of dead nodes is checked periodically. + +To customize the node selection behavior, provide a Selector implementation in the configuration. +To replace the connection pool entirely, provide a custom ConnectionPool implementation via +the ConnectionPoolFunc option. + +The package defines the Logger interface for logging information about request and response. +It comes with several bundled loggers for logging in text and JSON. + +Use the EnableDebugLogger option to enable the debugging logger for connection management. + +Use the EnableMetrics option to enable metric collection and export. +*/ +package opensearchtransport diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/gzip.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/gzip.go new file mode 100644 index 0000000000..d74cd07ec4 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/gzip.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchtransport + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "sync" +) + +type gzipCompressor struct { + gzipWriterPool *sync.Pool + bufferPool *sync.Pool +} + +// newGzipCompressor returns a new gzipCompressor that uses a sync.Pool to reuse gzip.Writers. +func newGzipCompressor() *gzipCompressor { + gzipWriterPool := sync.Pool{ + New: func() any { + return gzip.NewWriter(io.Discard) + }, + } + + bufferPool := sync.Pool{ + New: func() any { + return new(bytes.Buffer) + }, + } + + return &gzipCompressor{ + gzipWriterPool: &gzipWriterPool, + bufferPool: &bufferPool, + } +} + +func (pg *gzipCompressor) compress(rc io.ReadCloser) (*bytes.Buffer, error) { + writer := pg.gzipWriterPool.Get().(*gzip.Writer) + defer pg.gzipWriterPool.Put(writer) + + buf := pg.bufferPool.Get().(*bytes.Buffer) + buf.Reset() + writer.Reset(buf) + + if _, err := io.Copy(writer, rc); err != nil { + return nil, fmt.Errorf("failed to compress request body: %w", err) + } + if err := writer.Close(); err != nil { + return nil, fmt.Errorf("failed to compress request body (during close): %w", err) + } + return buf, nil +} + +func (pg *gzipCompressor) collectBuffer(buf *bytes.Buffer) { + pg.bufferPool.Put(buf) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/logger.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/logger.go new file mode 100644 index 0000000000..f7994e9d32 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/logger.go @@ -0,0 +1,449 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchtransport + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +var debugLogger DebuggingLogger + +// Logger defines an interface for logging request and response. +type Logger interface { + // LogRoundTrip should not modify the request or response, except for consuming and closing the body. + // Implementations have to check for nil values in request and response. + LogRoundTrip(*http.Request, *http.Response, error, time.Time, time.Duration) error + // RequestBodyEnabled makes the client pass a copy of request body to the logger. + RequestBodyEnabled() bool + // ResponseBodyEnabled makes the client pass a copy of response body to the logger. + ResponseBodyEnabled() bool +} + +// DebuggingLogger defines the interface for a debugging logger. +type DebuggingLogger interface { + Log(a ...interface{}) error + Logf(format string, a ...interface{}) error +} + +// TextLogger prints the log message in plain text. +type TextLogger struct { + Output io.Writer + EnableRequestBody bool + EnableResponseBody bool +} + +// ColorLogger prints the log message in a terminal-optimized plain text. +type ColorLogger struct { + Output io.Writer + EnableRequestBody bool + EnableResponseBody bool +} + +// CurlLogger prints the log message as a runnable curl command. +type CurlLogger struct { + Output io.Writer + EnableRequestBody bool + EnableResponseBody bool +} + +// JSONLogger prints the log message as JSON. +type JSONLogger struct { + Output io.Writer + EnableRequestBody bool + EnableResponseBody bool +} + +// debuggingLogger prints debug messages as plain text. +type debuggingLogger struct { + Output io.Writer +} + +// LogRoundTrip prints the information about request and response. +func (l *TextLogger) LogRoundTrip(req *http.Request, res *http.Response, err error, start time.Time, dur time.Duration) error { + fmt.Fprintf(l.Output, "%s %s %s [status:%d request:%s]\n", + start.Format(time.RFC3339), + req.Method, + req.URL.String(), + resStatusCode(res), + dur.Truncate(time.Millisecond), + ) + if l.RequestBodyEnabled() && req != nil && req.Body != nil && req.Body != http.NoBody { + var buf bytes.Buffer + if req.GetBody != nil { + b, _ := req.GetBody() + buf.ReadFrom(b) + } else { + buf.ReadFrom(req.Body) + } + logBodyAsText(l.Output, &buf, ">") + } + if l.ResponseBodyEnabled() && res != nil && res.Body != nil && res.Body != http.NoBody { + defer res.Body.Close() + var buf bytes.Buffer + buf.ReadFrom(res.Body) + logBodyAsText(l.Output, &buf, "<") + } + if err != nil { + fmt.Fprintf(l.Output, "! ERROR: %v\n", err) + } + return nil +} + +// RequestBodyEnabled returns true when the request body should be logged. +func (l *TextLogger) RequestBodyEnabled() bool { return l.EnableRequestBody } + +// ResponseBodyEnabled returns true when the response body should be logged. +func (l *TextLogger) ResponseBodyEnabled() bool { return l.EnableResponseBody } + +// LogRoundTrip prints the information about request and response. +func (l *ColorLogger) LogRoundTrip(req *http.Request, res *http.Response, err error, _ time.Time, dur time.Duration) error { + query, _ := url.QueryUnescape(req.URL.RawQuery) + if query != "" { + query = "?" + query + } + + var ( + status string + color string + ) + + status = res.Status + switch { + case res.StatusCode > 0 && res.StatusCode < 300: + color = "\x1b[32m" + case res.StatusCode > 299 && res.StatusCode < 500: + color = "\x1b[33m" + case res.StatusCode > 499: + color = "\x1b[31m" + default: + status = "ERROR" + color = "\x1b[31;4m" + } + + fmt.Fprintf(l.Output, "%6s \x1b[1;4m%s://%s%s\x1b[0m%s %s%s\x1b[0m \x1b[2m%s\x1b[0m\n", + req.Method, + req.URL.Scheme, + req.URL.Host, + req.URL.Path, + query, + color, + status, + dur.Truncate(time.Millisecond), + ) + + if l.RequestBodyEnabled() && req != nil && req.Body != nil && req.Body != http.NoBody { + var buf bytes.Buffer + if req.GetBody != nil { + b, _ := req.GetBody() + buf.ReadFrom(b) + } else { + buf.ReadFrom(req.Body) + } + fmt.Fprint(l.Output, "\x1b[2m") + logBodyAsText(l.Output, &buf, " »") + fmt.Fprint(l.Output, "\x1b[0m") + } + + if l.ResponseBodyEnabled() && res != nil && res.Body != nil && res.Body != http.NoBody { + defer res.Body.Close() + var buf bytes.Buffer + buf.ReadFrom(res.Body) + fmt.Fprint(l.Output, "\x1b[2m") + logBodyAsText(l.Output, &buf, " «") + fmt.Fprint(l.Output, "\x1b[0m") + } + + if err != nil { + fmt.Fprintf(l.Output, "\x1b[31;1m» ERROR \x1b[31m%v\x1b[0m\n", err) + } + + if l.RequestBodyEnabled() || l.ResponseBodyEnabled() { + fmt.Fprintf(l.Output, "\x1b[2m%s\x1b[0m\n", strings.Repeat("─", 80)) + } + return nil +} + +// RequestBodyEnabled returns true when the request body should be logged. +func (l *ColorLogger) RequestBodyEnabled() bool { return l.EnableRequestBody } + +// ResponseBodyEnabled returns true when the response body should be logged. +func (l *ColorLogger) ResponseBodyEnabled() bool { return l.EnableResponseBody } + +// LogRoundTrip prints the information about request and response. +func (l *CurlLogger) LogRoundTrip(req *http.Request, res *http.Response, _ error, start time.Time, dur time.Duration) error { + var b bytes.Buffer + + var query string + qvalues := url.Values{} + for k, v := range req.URL.Query() { + if k == "pretty" { + continue + } + for _, qv := range v { + qvalues.Add(k, qv) + } + } + if len(qvalues) > 0 { + query = qvalues.Encode() + } + + b.WriteString(`curl`) + if req.Method == http.MethodHead { + b.WriteString(" --head") + } else { + fmt.Fprintf(&b, " -X %s", req.Method) + } + + if len(req.Header) > 0 { + for k, vv := range req.Header { + if k == "Authorization" || k == "User-Agent" { + continue + } + v := strings.Join(vv, ",") + b.WriteString(fmt.Sprintf(" -H '%s: %s'", k, v)) + } + } + + // If by some oddity we end up with a nil req.URL, we handle it gracefully. + if req.URL == nil { + b.WriteString(" '") + } else { + b.WriteString(fmt.Sprintf(" '%s://%s%s", req.URL.Scheme, req.URL.Host, req.URL.Path)) + } + b.WriteString("?pretty") + if query != "" { + fmt.Fprintf(&b, "&%s", query) + } + b.WriteString("'") + + if req != nil && req.Body != nil && req.Body != http.NoBody { + var buf bytes.Buffer + if req.GetBody != nil { + b, _ := req.GetBody() + buf.ReadFrom(b) + } else { + buf.ReadFrom(req.Body) + } + + b.Grow(buf.Len()) + b.WriteString(" -d \\\n'") + json.Indent(&b, buf.Bytes(), "", " ") + b.WriteString("'") + } + + b.WriteRune('\n') + + status := res.Status + + fmt.Fprintf(&b, "# => %s [%s] %s\n", start.UTC().Format(time.RFC3339), status, dur.Truncate(time.Millisecond)) + if l.ResponseBodyEnabled() && res != nil && res.Body != nil && res.Body != http.NoBody { + var buf bytes.Buffer + buf.ReadFrom(res.Body) + + b.Grow(buf.Len()) + b.WriteString("# ") + json.Indent(&b, buf.Bytes(), "# ", " ") + } + + b.WriteString("\n") + if l.ResponseBodyEnabled() && res != nil && res.Body != nil && res.Body != http.NoBody { + b.WriteString("\n") + } + + b.WriteTo(l.Output) + + return nil +} + +// RequestBodyEnabled returns true when the request body should be logged. +func (l *CurlLogger) RequestBodyEnabled() bool { return l.EnableRequestBody } + +// ResponseBodyEnabled returns true when the response body should be logged. +func (l *CurlLogger) ResponseBodyEnabled() bool { return l.EnableResponseBody } + +// LogRoundTrip prints the information about request and response. +func (l *JSONLogger) LogRoundTrip(req *http.Request, res *http.Response, err error, start time.Time, dur time.Duration) error { + // TODO: Research performance optimization of using sync.Pool + + bsize := 200 + b := bytes.NewBuffer(make([]byte, 0, bsize)) + v := make([]byte, 0, bsize) + + appendTime := func(t time.Time) { + v = v[:0] + v = t.AppendFormat(v, time.RFC3339) + b.Write(v) + } + + appendQuote := func(s string) { + v = v[:0] + v = strconv.AppendQuote(v, s) + b.Write(v) + } + + appendInt := func(i int64) { + v = v[:0] + v = strconv.AppendInt(v, i, 10) + b.Write(v) + } + + b.WriteRune('{') + // -- Timestamp + b.WriteString(`"@timestamp":"`) + appendTime(start.UTC()) + b.WriteRune('"') + // -- Event + b.WriteString(`,"event":{`) + b.WriteString(`"duration":`) + appendInt(dur.Nanoseconds()) + b.WriteRune('}') + // -- URL + b.WriteString(`,"url":{`) + b.WriteString(`"scheme":`) + appendQuote(req.URL.Scheme) + b.WriteString(`,"domain":`) + appendQuote(req.URL.Hostname()) + if port := req.URL.Port(); port != "" { + b.WriteString(`,"port":`) + b.WriteString(port) + } + b.WriteString(`,"path":`) + appendQuote(req.URL.Path) + b.WriteString(`,"query":`) + appendQuote(req.URL.RawQuery) + b.WriteRune('}') // Close "url" + // -- HTTP + b.WriteString(`,"http":`) + // ---- Request + b.WriteString(`{"request":{`) + b.WriteString(`"method":`) + appendQuote(req.Method) + if l.RequestBodyEnabled() && req != nil && req.Body != nil && req.Body != http.NoBody { + var buf bytes.Buffer + if req.GetBody != nil { + b, _ := req.GetBody() + buf.ReadFrom(b) + } else { + buf.ReadFrom(req.Body) + } + + b.Grow(buf.Len() + 8) + b.WriteString(`,"body":`) + appendQuote(buf.String()) + } + b.WriteRune('}') // Close "http.request" + // ---- Response + b.WriteString(`,"response":{`) + b.WriteString(`"status_code":`) + appendInt(int64(resStatusCode(res))) + if l.ResponseBodyEnabled() && res != nil && res.Body != nil && res.Body != http.NoBody { + defer res.Body.Close() + var buf bytes.Buffer + buf.ReadFrom(res.Body) + + b.Grow(buf.Len() + 8) + b.WriteString(`,"body":`) + appendQuote(buf.String()) + } + b.WriteRune('}') // Close "http.response" + b.WriteRune('}') // Close "http" + // -- Error + if err != nil { + b.WriteString(`,"error":{"message":`) + appendQuote(err.Error()) + b.WriteRune('}') // Close "error" + } + b.WriteRune('}') + b.WriteRune('\n') + b.WriteTo(l.Output) + + return nil +} + +// RequestBodyEnabled returns true when the request body should be logged. +func (l *JSONLogger) RequestBodyEnabled() bool { return l.EnableRequestBody } + +// ResponseBodyEnabled returns true when the response body should be logged. +func (l *JSONLogger) ResponseBodyEnabled() bool { return l.EnableResponseBody } + +// Log prints the arguments to output in default format. +func (l *debuggingLogger) Log(a ...interface{}) error { + _, err := fmt.Fprint(l.Output, a...) + return err +} + +// Logf prints formats the arguments and prints them to output. +func (l *debuggingLogger) Logf(format string, a ...interface{}) error { + _, err := fmt.Fprintf(l.Output, format, a...) + return err +} + +func logBodyAsText(dst io.Writer, body io.Reader, prefix string) { + scanner := bufio.NewScanner(body) + for scanner.Scan() { + s := scanner.Text() + if s != "" { + fmt.Fprintf(dst, "%s %s\n", prefix, s) + } + } +} + +func duplicateBody(body io.ReadCloser) (io.ReadCloser, io.ReadCloser, error) { + var ( + b1 bytes.Buffer + b2 bytes.Buffer + tr = io.TeeReader(body, &b2) + ) + + if _, err := b1.ReadFrom(tr); err != nil { + return io.NopCloser(io.MultiReader(&b1, errorReader{err: err})), io.NopCloser(io.MultiReader(&b2, errorReader{err: err})), err + } + + defer func() { body.Close() }() + + return io.NopCloser(&b1), io.NopCloser(&b2), nil +} + +func resStatusCode(res *http.Response) int { + if res == nil { + return -1 + } + return res.StatusCode +} + +type errorReader struct{ err error } + +func (r errorReader) Read(_ []byte) (int, error) { return 0, r.err } diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/metrics.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/metrics.go new file mode 100644 index 0000000000..442d04ae59 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/metrics.go @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchtransport + +import ( + "errors" + "fmt" + "strconv" + "strings" + "sync" + "time" +) + +// Measurable defines the interface for transports supporting metrics. +type Measurable interface { + Metrics() (Metrics, error) +} + +// connectionable defines the interface for transports returning a list of connections. +type connectionable interface { + connections() []*Connection +} + +// Metrics represents the transport metrics. +type Metrics struct { + Requests int `json:"requests"` + Failures int `json:"failures"` + Responses map[int]int `json:"responses"` + + Connections []fmt.Stringer `json:"connections"` +} + +// ConnectionMetric represents metric information for a connection. +type ConnectionMetric struct { + URL string `json:"url"` + Failures int `json:"failures,omitempty"` + IsDead bool `json:"dead,omitempty"` + DeadSince *time.Time `json:"dead_since,omitempty"` + + Meta struct { + ID string `json:"id"` + Name string `json:"name"` + Roles []string `json:"roles"` + } `json:"meta"` +} + +// metrics represents the inner state of metrics. +type metrics struct { + sync.RWMutex + + requests int + failures int + responses map[int]int +} + +// Metrics returns the transport metrics. +func (c *Client) Metrics() (Metrics, error) { + if c.metrics == nil { + return Metrics{}, errors.New("transport metrics not enabled") + } + c.metrics.RLock() + defer c.metrics.RUnlock() + + if lockable, ok := c.pool.(sync.Locker); ok { + lockable.Lock() + defer lockable.Unlock() + } + + m := Metrics{ + Requests: c.metrics.requests, + Failures: c.metrics.failures, + Responses: c.metrics.responses, + } + + if pool, ok := c.pool.(connectionable); ok { + connections := pool.connections() + for idx, c := range connections { + c.Lock() + + cm := ConnectionMetric{ + URL: c.URL.String(), + IsDead: c.IsDead, + Failures: c.Failures, + } + + if !c.DeadSince.IsZero() { + cm.DeadSince = &connections[idx].DeadSince + } + + if c.ID != "" { + cm.Meta.ID = c.ID + } + + if c.Name != "" { + cm.Meta.Name = c.Name + } + + if len(c.Roles) > 0 { + cm.Meta.Roles = c.Roles + } + + m.Connections = append(m.Connections, cm) + c.Unlock() + } + } + + return m, nil +} + +// String returns the metrics as a string. +func (m Metrics) String() string { + var ( + i int + b strings.Builder + ) + b.WriteString("{") + + b.WriteString("Requests:") + b.WriteString(strconv.Itoa(m.Requests)) + + b.WriteString(" Failures:") + b.WriteString(strconv.Itoa(m.Failures)) + + if len(m.Responses) > 0 { + b.WriteString(" Responses: ") + b.WriteString("[") + + for code, num := range m.Responses { + b.WriteString(strconv.Itoa(code)) + b.WriteString(":") + b.WriteString(strconv.Itoa(num)) + if i+1 < len(m.Responses) { + b.WriteString(", ") + } + i++ + } + b.WriteString("]") + } + + b.WriteString(" Connections: [") + for i, c := range m.Connections { + b.WriteString(c.String()) + if i+1 < len(m.Connections) { + b.WriteString(", ") + } + } + b.WriteString("]") + + b.WriteString("}") + return b.String() +} + +// String returns the connection information as a string. +func (cm ConnectionMetric) String() string { + var b strings.Builder + b.WriteString("{") + b.WriteString(cm.URL) + if cm.IsDead { + fmt.Fprintf(&b, " dead=%v", cm.IsDead) + } + if cm.Failures > 0 { + fmt.Fprintf(&b, " failures=%d", cm.Failures) + } + if cm.DeadSince != nil { + fmt.Fprintf(&b, " dead_since=%s", cm.DeadSince.Local().Format(time.Stamp)) + } + b.WriteString("}") + return b.String() +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/opensearchtransport.go b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/opensearchtransport.go new file mode 100644 index 0000000000..82571435b0 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/opensearchtransport/opensearchtransport.go @@ -0,0 +1,515 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchtransport + +import ( + "bytes" + "crypto/x509" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/opensearch-project/opensearch-go/v4/internal/version" + "github.com/opensearch-project/opensearch-go/v4/signer" +) + +const ( + // Version returns the package version as a string. + Version = version.Client + defaultMaxRetries = 3 +) + +var reGoVersion = regexp.MustCompile(`go(\d+\.\d+\..+)`) + +// Interface defines the interface for HTTP client. +type Interface interface { + Perform(*http.Request) (*http.Response, error) +} + +// Config represents the configuration of HTTP client. +type Config struct { + URLs []*url.URL + Username string + Password string + + Header http.Header + CACert []byte + + Signer signer.Signer + + RetryOnStatus []int + DisableRetry bool + EnableRetryOnTimeout bool + MaxRetries int + RetryBackoff func(attempt int) time.Duration + + CompressRequestBody bool + + EnableMetrics bool + EnableDebugLogger bool + + DiscoverNodesInterval time.Duration + + Transport http.RoundTripper + Logger Logger + Selector Selector + + ConnectionPoolFunc func([]*Connection, Selector) ConnectionPool +} + +// Client represents the HTTP client. +type Client struct { + sync.Mutex + + urls []*url.URL + username string + password string + header http.Header + userAgent string + + signer signer.Signer + + retryOnStatus []int + disableRetry bool + enableRetryOnTimeout bool + maxRetries int + retryBackoff func(attempt int) time.Duration + discoverNodesInterval time.Duration + discoverNodesTimer *time.Timer + + compressRequestBody bool + pooledGzipCompressor *gzipCompressor + + metrics *metrics + + transport http.RoundTripper + logger Logger + selector Selector + pool ConnectionPool + poolFunc func([]*Connection, Selector) ConnectionPool +} + +// New creates new transport client. +// +// http.DefaultTransport will be used if no transport is passed in the configuration. +func New(cfg Config) (*Client, error) { + if cfg.Transport == nil { + cfg.Transport = http.DefaultTransport + } + + if cfg.CACert != nil { + httpTransport, ok := cfg.Transport.(*http.Transport) + if !ok { + return nil, fmt.Errorf("unable to set CA certificate for transport of type %T", cfg.Transport) + } + + httpTransport = httpTransport.Clone() + httpTransport.TLSClientConfig.RootCAs = x509.NewCertPool() + + if ok := httpTransport.TLSClientConfig.RootCAs.AppendCertsFromPEM(cfg.CACert); !ok { + return nil, errors.New("unable to add CA certificate") + } + + cfg.Transport = httpTransport + } + + if len(cfg.RetryOnStatus) == 0 && cfg.RetryOnStatus == nil { + cfg.RetryOnStatus = []int{502, 503, 504} + } + + if cfg.MaxRetries == 0 { + cfg.MaxRetries = defaultMaxRetries + } + + conns := make([]*Connection, len(cfg.URLs)) + for idx, u := range cfg.URLs { + conns[idx] = &Connection{URL: u} + } + + client := Client{ + urls: cfg.URLs, + username: cfg.Username, + password: cfg.Password, + header: cfg.Header, + + signer: cfg.Signer, + + retryOnStatus: cfg.RetryOnStatus, + disableRetry: cfg.DisableRetry, + enableRetryOnTimeout: cfg.EnableRetryOnTimeout, + maxRetries: cfg.MaxRetries, + retryBackoff: cfg.RetryBackoff, + discoverNodesInterval: cfg.DiscoverNodesInterval, + + compressRequestBody: cfg.CompressRequestBody, + + transport: cfg.Transport, + logger: cfg.Logger, + selector: cfg.Selector, + poolFunc: cfg.ConnectionPoolFunc, + } + + client.userAgent = initUserAgent() + + if client.poolFunc != nil { + client.pool = client.poolFunc(conns, client.selector) + } else { + client.pool = NewConnectionPool(conns, client.selector) + } + + if cfg.EnableDebugLogger { + debugLogger = &debuggingLogger{Output: os.Stdout} + } + + if cfg.EnableMetrics { + client.metrics = &metrics{responses: make(map[int]int)} + // TODO(karmi): Type assertion to interface + if pool, ok := client.pool.(*singleConnectionPool); ok { + pool.metrics = client.metrics + } + if pool, ok := client.pool.(*statusConnectionPool); ok { + pool.metrics = client.metrics + } + } + + if client.discoverNodesInterval > 0 { + time.AfterFunc(client.discoverNodesInterval, func() { + client.scheduleDiscoverNodes() + }) + } + + if cfg.CompressRequestBody { + client.pooledGzipCompressor = newGzipCompressor() + } + + return &client, nil +} + +// Perform executes the request and returns a response or error. +func (c *Client) Perform(req *http.Request) (*http.Response, error) { + var ( + res *http.Response + err error + ) + + // Record metrics, when enabled + if c.metrics != nil { + c.metrics.Lock() + c.metrics.requests++ + c.metrics.Unlock() + } + + // Update request + c.setReqUserAgent(req) + c.setReqGlobalHeader(req) + + if req.Body != nil && req.Body != http.NoBody { + if c.compressRequestBody { + buf, err := c.pooledGzipCompressor.compress(req.Body) + defer c.pooledGzipCompressor.collectBuffer(buf) + if err != nil { + return nil, fmt.Errorf("failed to compress request body: %w", err) + } + + req.GetBody = func() (io.ReadCloser, error) { + // We have to return a new reader each time so that retries don't read from an already-consumed body. + reader := bytes.NewReader(buf.Bytes()) + return io.NopCloser(reader), nil + } + //nolint:errcheck // error is always nil + req.Body, _ = req.GetBody() + + req.Header.Set("Content-Encoding", "gzip") + req.ContentLength = int64(buf.Len()) + } else if req.GetBody == nil { + if !c.disableRetry || (c.logger != nil && c.logger.RequestBodyEnabled()) { + var buf bytes.Buffer + //nolint:errcheck // ignored as this is only for logging + buf.ReadFrom(req.Body) + req.GetBody = func() (io.ReadCloser, error) { + // Return a new reader each time + reader := bytes.NewReader(buf.Bytes()) + return io.NopCloser(reader), nil + } + //nolint:errcheck // error is always nil + req.Body, _ = req.GetBody() + } + } + } + + for i := 0; i <= c.maxRetries; i++ { + var ( + conn *Connection + shouldRetry bool + shouldCloseBody bool + ) + + // Get connection from the pool + c.Lock() + conn, err = c.pool.Next() + c.Unlock() + if err != nil { + if c.logger != nil { + c.logRoundTrip(req, nil, err, time.Time{}, time.Duration(0)) + } + return nil, fmt.Errorf("cannot get connection: %w", err) + } + + // Update request + c.setReqURL(conn.URL, req) + c.setReqAuth(conn.URL, req) + + if !c.disableRetry && i > 0 && req.Body != nil && req.Body != http.NoBody { + body, err := req.GetBody() + if err != nil { + return nil, fmt.Errorf("cannot get request body: %w", err) + } + req.Body = body + } + + if err = c.signRequest(req); err != nil { + return nil, fmt.Errorf("failed to sign request: %w", err) + } + + // Set up time measures and execute the request + start := time.Now().UTC() + res, err = c.transport.RoundTrip(req) + dur := time.Since(start) + + // Log request and response + if c.logger != nil { + if c.logger.RequestBodyEnabled() && req.Body != nil && req.Body != http.NoBody { + //nolint:errcheck // ignored as this is only for logging + req.Body, _ = req.GetBody() + } + c.logRoundTrip(req, res, err, start, dur) + } + + if err != nil { + // Record metrics, when enabled + if c.metrics != nil { + c.metrics.Lock() + c.metrics.failures++ + c.metrics.Unlock() + } + + // Report the connection as unsuccessful + c.Lock() + //nolint:errcheck // Questionable if the function even returns an error + c.pool.OnFailure(conn) + c.Unlock() + + // Retry on EOF errors + if errors.Is(err, io.EOF) { + shouldRetry = true + } + + // Retry on network errors, but not on timeout errors, unless configured + var netError net.Error + if errors.As(err, &netError) { + if (!netError.Timeout() || c.enableRetryOnTimeout) && !c.disableRetry { + shouldRetry = true + } + } + } else { + // Report the connection as succesfull + c.Lock() + c.pool.OnSuccess(conn) + c.Unlock() + } + + if res != nil && c.metrics != nil { + c.metrics.Lock() + c.metrics.responses[res.StatusCode]++ + c.metrics.Unlock() + } + + // Retry on configured response statuses + if res != nil && !c.disableRetry { + for _, code := range c.retryOnStatus { + if res.StatusCode == code { + shouldRetry = true + shouldCloseBody = true + } + } + } + + // Break if retry should not be performed + if !shouldRetry { + break + } + + // Drain and close body when retrying after response + if shouldCloseBody && i < c.maxRetries { + if res.Body != nil { + //nolint:errcheck // undexpected but okay if it failes + io.Copy(io.Discard, res.Body) + res.Body.Close() + } + } + + // Delay the retry if a backoff function is configured + if c.retryBackoff != nil && i < c.maxRetries { + var cancelled bool + timer := time.NewTimer(c.retryBackoff(i + 1)) + select { + case <-req.Context().Done(): + timer.Stop() + err = req.Context().Err() + cancelled = true + case <-timer.C: + } + if cancelled { + break + } + } + } + // Read, close and replace the http response body to close the connection + if res != nil && res.Body != nil { + body, err := io.ReadAll(res.Body) + res.Body.Close() + if err == nil { + res.Body = io.NopCloser(bytes.NewReader(body)) + } + } + + // TODO(karmi): Wrap error + return res, err +} + +// URLs returns a list of transport URLs. +func (c *Client) URLs() []*url.URL { + return c.pool.URLs() +} + +func (c *Client) setReqURL(u *url.URL, req *http.Request) { + req.URL.Scheme = u.Scheme + req.URL.Host = u.Host + + if u.Path != "" { + var b strings.Builder + b.Grow(len(u.Path) + len(req.URL.Path)) + b.WriteString(u.Path) + b.WriteString(req.URL.Path) + req.URL.Path = b.String() + } +} + +func (c *Client) setReqAuth(u *url.URL, req *http.Request) { + if _, ok := req.Header["Authorization"]; !ok { + if u.User != nil { + password, _ := u.User.Password() + req.SetBasicAuth(u.User.Username(), password) + return + } + + if c.username != "" && c.password != "" { + req.SetBasicAuth(c.username, c.password) + return + } + } +} + +func (c *Client) signRequest(req *http.Request) error { + if c.signer != nil { + return c.signer.SignRequest(req) + } + return nil +} + +func (c *Client) setReqUserAgent(req *http.Request) { + req.Header.Set("User-Agent", c.userAgent) +} + +func (c *Client) setReqGlobalHeader(req *http.Request) { + if len(c.header) > 0 { + for k, v := range c.header { + if req.Header.Get(k) != k { + for _, vv := range v { + req.Header.Add(k, vv) + } + } + } + } +} + +func (c *Client) logRoundTrip( + req *http.Request, + res *http.Response, + err error, + start time.Time, + dur time.Duration, +) { + var dupRes http.Response + if res != nil { + dupRes = *res + } + + if c.logger.ResponseBodyEnabled() { + if res != nil && res.Body != nil && res.Body != http.NoBody { + //nolint:errcheck // ignored as this is only for logging + b1, b2, _ := duplicateBody(res.Body) + dupRes.Body = b1 + res.Body = b2 + } + } + + //nolint:errcheck // ignored as this is only for logging + c.logger.LogRoundTrip(req, &dupRes, err, start, dur) +} + +func initUserAgent() string { + var b strings.Builder + + b.WriteString("opensearch-go") + b.WriteRune('/') + b.WriteString(Version) + b.WriteRune(' ') + b.WriteRune('(') + b.WriteString(runtime.GOOS) + b.WriteRune(' ') + b.WriteString(runtime.GOARCH) + b.WriteString("; ") + b.WriteString("Go ") + if v := reGoVersion.ReplaceAllString(runtime.Version(), "$1"); v != "" { + b.WriteString(v) + } else { + b.WriteString(runtime.Version()) + } + b.WriteRune(')') + + return b.String() +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/request.go b/vendor/github.com/opensearch-project/opensearch-go/v4/request.go new file mode 100644 index 0000000000..1e2dc4af66 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/request.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "net/http" +) + +// Request represents a requests the client can execute +type Request interface { + GetRequest() (*http.Request, error) +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/request_builder.go b/vendor/github.com/opensearch-project/opensearch-go/v4/request_builder.go new file mode 100644 index 0000000000..ebfc1b80d6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/request_builder.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "io" + "net/http" +) + +const ( + headerContentType = "Content-Type" +) + +// BuildRequest is a helper function to build a http.Request +func BuildRequest(method string, path string, body io.Reader, params map[string]string, headers http.Header) (*http.Request, error) { + //nolint:noctx // ctx gets appended when the requests gets executet + httpReq, err := http.NewRequest(method, path, body) + if err != nil { + return nil, err + } + + if len(params) > 0 { + q := httpReq.URL.Query() + for k, v := range params { + q.Set(k, v) + } + + httpReq.URL.RawQuery = q.Encode() + } + + if body != nil { + httpReq.Header[headerContentType] = []string{"application/json"} + } + + if len(headers) > 0 { + if len(httpReq.Header) == 0 { + httpReq.Header = headers + } else { + for k, vv := range headers { + for _, v := range vv { + httpReq.Header.Add(k, v) + } + } + } + } + return httpReq, nil +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/response.go b/vendor/github.com/opensearch-project/opensearch-go/v4/response.go new file mode 100644 index 0000000000..db4d0191d6 --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/response.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "fmt" + "io" + "net/http" +) + +const httpStatusCodeThreshold = 299 + +// Response represents the API response. +type Response struct { + StatusCode int + Header http.Header + Body io.ReadCloser +} + +// String returns the response as a string. +func (r Response) String() string { + if r.Body != nil { + body, err := io.ReadAll(r.Body) + if err != nil { + body = []byte(fmt.Sprintf("", err)) + } + return fmt.Sprintf("%s %s", r.Status(), body) + } + return r.Status() +} + +// Status retuens the response status as string. +func (r Response) Status() string { + status := http.StatusText(r.StatusCode) + if status == "" { + status = "" + } + return fmt.Sprintf("[%d %s]", r.StatusCode, status) +} + +// IsError returns true when the response status indicates failure. +func (r *Response) IsError() bool { + return r.StatusCode > httpStatusCodeThreshold +} diff --git a/vendor/github.com/opensearch-project/opensearch-go/v4/signer/signer.go b/vendor/github.com/opensearch-project/opensearch-go/v4/signer/signer.go new file mode 100644 index 0000000000..8a5beb94fd --- /dev/null +++ b/vendor/github.com/opensearch-project/opensearch-go/v4/signer/signer.go @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +package signer + +import "net/http" + +// Signer an interface that will sign http.Request +type Signer interface { + SignRequest(request *http.Request) error +} diff --git a/vendor/github.com/samber/lo/.gitignore b/vendor/github.com/samber/lo/.gitignore new file mode 100644 index 0000000000..e5ecc5c40a --- /dev/null +++ b/vendor/github.com/samber/lo/.gitignore @@ -0,0 +1,38 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/go +# Edit at https://www.toptal.com/developers/gitignore?templates=go + +### Go ### +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work + +### Go Patch ### +/vendor/ +/Godeps/ + +# End of https://www.toptal.com/developers/gitignore/api/go + +cover.out +cover.html +.vscode + +.idea/ diff --git a/vendor/github.com/samber/lo/Dockerfile b/vendor/github.com/samber/lo/Dockerfile new file mode 100644 index 0000000000..5dbeb415bd --- /dev/null +++ b/vendor/github.com/samber/lo/Dockerfile @@ -0,0 +1,8 @@ + +FROM golang:1.23.1 + +WORKDIR /go/src/github.com/samber/lo + +COPY Makefile go.* ./ + +RUN make tools diff --git a/vendor/github.com/samber/lo/LICENSE b/vendor/github.com/samber/lo/LICENSE new file mode 100644 index 0000000000..2e3ebd5e83 --- /dev/null +++ b/vendor/github.com/samber/lo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022-2025 Samuel Berthe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/samber/lo/Makefile b/vendor/github.com/samber/lo/Makefile new file mode 100644 index 0000000000..f97ded85e7 --- /dev/null +++ b/vendor/github.com/samber/lo/Makefile @@ -0,0 +1,42 @@ + +build: + go build -v ./... + +test: + go test -race -v ./... +watch-test: + reflex -t 50ms -s -- sh -c 'gotest -race -v ./...' + +bench: + go test -benchmem -count 3 -bench ./... +watch-bench: + reflex -t 50ms -s -- sh -c 'go test -benchmem -count 3 -bench ./...' + +coverage: + go test -v -coverprofile=cover.out -covermode=atomic ./... + go tool cover -html=cover.out -o cover.html + +# tools +tools: + go install github.com/cespare/reflex@latest + go install github.com/rakyll/gotest@latest + go install github.com/psampaz/go-mod-outdated@latest + go install github.com/jondot/goweight@latest + go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + go get -t -u golang.org/x/tools/cmd/cover + go install github.com/sonatype-nexus-community/nancy@latest + go mod tidy + +lint: + golangci-lint run --timeout 60s --max-same-issues 50 ./... +lint-fix: + golangci-lint run --timeout 60s --max-same-issues 50 --fix ./... + +audit: tools + go list -json -m all | nancy sleuth + +outdated: tools + go list -u -m -json all | go-mod-outdated -update -direct + +weight: tools + goweight diff --git a/vendor/github.com/samber/lo/README.md b/vendor/github.com/samber/lo/README.md new file mode 100644 index 0000000000..87d25509f8 --- /dev/null +++ b/vendor/github.com/samber/lo/README.md @@ -0,0 +1,4213 @@ + +# lo - Iterate over slices, maps, channels... + +[![tag](https://img.shields.io/github/tag/samber/lo.svg)](https://github.com/samber/lo/releases) +![Go Version](https://img.shields.io/badge/Go-%3E%3D%201.18-%23007d9c) +[![GoDoc](https://godoc.org/github.com/samber/lo?status.svg)](https://pkg.go.dev/github.com/samber/lo) +![Build Status](https://github.com/samber/lo/actions/workflows/test.yml/badge.svg) +[![Go report](https://goreportcard.com/badge/github.com/samber/lo)](https://goreportcard.com/report/github.com/samber/lo) +[![Coverage](https://img.shields.io/codecov/c/github/samber/lo)](https://codecov.io/gh/samber/lo) +[![Contributors](https://img.shields.io/github/contributors/samber/lo)](https://github.com/samber/lo/graphs/contributors) +[![License](https://img.shields.io/github/license/samber/lo)](./LICENSE) + +✨ **`samber/lo` is a Lodash-style Go library based on Go 1.18+ Generics.** + +A utility library based on Go 1.18+ generics that makes it easier to work with slices, maps, strings, channels, and functions. It provides dozens of handy methods to simplify common coding tasks and improve code readability. It may look like [Lodash](https://github.com/lodash/lodash) in some aspects. + +5 to 10 helpers may overlap with those from the Go standard library, in packages `slices` and `maps`. I feel this library is legitimate and offers many more valuable abstractions. + +**See also:** + +- [samber/do](https://github.com/samber/do): A dependency injection toolkit based on Go 1.18+ Generics +- [samber/mo](https://github.com/samber/mo): Monads based on Go 1.18+ Generics (Option, Result, Either...) + +**Why this name?** + +I wanted a **short name**, similar to "Lodash", and no Go package uses this name. + +![lo](img/logo-full.png) + +## 🚀 Install + +```sh +go get github.com/samber/lo@v1 +``` + +This library is v1 and follows SemVer strictly. + +No breaking changes will be made to exported APIs before v2.0.0. + +This library has no dependencies outside the Go standard library. + +## 💡 Usage + +You can import `lo` using: + +```go +import ( + "github.com/samber/lo" + lop "github.com/samber/lo/parallel" + lom "github.com/samber/lo/mutable" +) +``` + +Then use one of the helpers below: + +```go +names := lo.Uniq([]string{"Samuel", "John", "Samuel"}) +// []string{"Samuel", "John"} +``` + +### Tips for lazy developers + +I cannot recommend it, but in case you are too lazy for repeating `lo.` everywhere, you can import the entire library into the namespace. + +```go +import ( + . "github.com/samber/lo" +) +``` + +I take no responsibility on this junk. 😁 💩 + +## 🤠 Spec + +GoDoc: [https://godoc.org/github.com/samber/lo](https://godoc.org/github.com/samber/lo) + +Supported helpers for slices: + +- [Filter](#filter) +- [Map](#map) +- [UniqMap](#uniqmap) +- [FilterMap](#filtermap) +- [FlatMap](#flatmap) +- [Reduce](#reduce) +- [ReduceRight](#reduceright) +- [ForEach](#foreach) +- [ForEachWhile](#foreachwhile) +- [Times](#times) +- [Uniq](#uniq) +- [UniqBy](#uniqby) +- [GroupBy](#groupby) +- [GroupByMap](#groupbymap) +- [Chunk](#chunk) +- [PartitionBy](#partitionby) +- [Flatten](#flatten) +- [Interleave](#interleave) +- [Shuffle](#shuffle) +- [Reverse](#reverse) +- [Fill](#fill) +- [Repeat](#repeat) +- [RepeatBy](#repeatby) +- [KeyBy](#keyby) +- [SliceToMap / Associate](#slicetomap-alias-associate) +- [FilterSliceToMap](#filterslicetomap) +- [Keyify](#keyify) +- [Drop](#drop) +- [DropRight](#dropright) +- [DropWhile](#dropwhile) +- [DropRightWhile](#droprightwhile) +- [DropByIndex](#DropByIndex) +- [Reject](#reject) +- [RejectMap](#rejectmap) +- [FilterReject](#filterreject) +- [Count](#count) +- [CountBy](#countby) +- [CountValues](#countvalues) +- [CountValuesBy](#countvaluesby) +- [Subset](#subset) +- [Slice](#slice) +- [Replace](#replace) +- [ReplaceAll](#replaceall) +- [Compact](#compact) +- [IsSorted](#issorted) +- [IsSortedByKey](#issortedbykey) +- [Splice](#Splice) + +Supported helpers for maps: + +- [Keys](#keys) +- [UniqKeys](#uniqkeys) +- [HasKey](#haskey) +- [ValueOr](#valueor) +- [Values](#values) +- [UniqValues](#uniqvalues) +- [PickBy](#pickby) +- [PickByKeys](#pickbykeys) +- [PickByValues](#pickbyvalues) +- [OmitBy](#omitby) +- [OmitByKeys](#omitbykeys) +- [OmitByValues](#omitbyvalues) +- [Entries / ToPairs](#entries-alias-topairs) +- [FromEntries / FromPairs](#fromentries-alias-frompairs) +- [Invert](#invert) +- [Assign (merge of maps)](#assign) +- [MapKeys](#mapkeys) +- [MapValues](#mapvalues) +- [MapEntries](#mapentries) +- [MapToSlice](#maptoslice) +- [FilterMapToSlice](#FilterMapToSlice) + +Supported math helpers: + +- [Range / RangeFrom / RangeWithSteps](#range--rangefrom--rangewithsteps) +- [Clamp](#clamp) +- [Sum](#sum) +- [SumBy](#sumby) +- [Product](#product) +- [ProductBy](#productby) +- [Mean](#mean) +- [MeanBy](#meanby) + +Supported helpers for strings: + +- [RandomString](#randomstring) +- [Substring](#substring) +- [ChunkString](#chunkstring) +- [RuneLength](#runelength) +- [PascalCase](#pascalcase) +- [CamelCase](#camelcase) +- [KebabCase](#kebabcase) +- [SnakeCase](#snakecase) +- [Words](#words) +- [Capitalize](#capitalize) +- [Ellipsis](#ellipsis) + +Supported helpers for tuples: + +- [T2 -> T9](#t2---t9) +- [Unpack2 -> Unpack9](#unpack2---unpack9) +- [Zip2 -> Zip9](#zip2---zip9) +- [ZipBy2 -> ZipBy9](#zipby2---zipby9) +- [Unzip2 -> Unzip9](#unzip2---unzip9) +- [UnzipBy2 -> UnzipBy9](#unzipby2---unzipby9) +- [CrossJoin2 -> CrossJoin2](#crossjoin2---crossjoin9) +- [CrossJoinBy2 -> CrossJoinBy2](#crossjoinby2---crossjoinby9) + +Supported helpers for time and duration: + +- [Duration](#duration) +- [Duration0 -> Duration10](#duration0---duration10) + +Supported helpers for channels: + +- [ChannelDispatcher](#channeldispatcher) +- [SliceToChannel](#slicetochannel) +- [Generator](#generator) +- [Buffer](#buffer) +- [BufferWithContext](#bufferwithcontext) +- [BufferWithTimeout](#bufferwithtimeout) +- [FanIn](#fanin) +- [FanOut](#fanout) + +Supported intersection helpers: + +- [Contains](#contains) +- [ContainsBy](#containsby) +- [Every](#every) +- [EveryBy](#everyby) +- [Some](#some) +- [SomeBy](#someby) +- [None](#none) +- [NoneBy](#noneby) +- [Intersect](#intersect) +- [Difference](#difference) +- [Union](#union) +- [Without](#without) +- [WithoutBy](#withoutby) +- [WithoutEmpty](#withoutempty) +- [WithoutNth](#withoutnth) +- [ElementsMatch](#ElementsMatch) +- [ElementsMatchBy](#ElementsMatchBy) + +Supported search helpers: + +- [IndexOf](#indexof) +- [LastIndexOf](#lastindexof) +- [Find](#find) +- [FindIndexOf](#findindexof) +- [FindLastIndexOf](#findlastindexof) +- [FindOrElse](#findorelse) +- [FindKey](#findkey) +- [FindKeyBy](#findkeyby) +- [FindUniques](#finduniques) +- [FindUniquesBy](#finduniquesby) +- [FindDuplicates](#findduplicates) +- [FindDuplicatesBy](#findduplicatesby) +- [Min](#min) +- [MinIndex](#minindex) +- [MinBy](#minby) +- [MinIndexBy](#minindexby) +- [Earliest](#earliest) +- [EarliestBy](#earliestby) +- [Max](#max) +- [MaxIndex](#maxindex) +- [MaxBy](#maxby) +- [MaxIndexBy](#maxindexby) +- [Latest](#latest) +- [LatestBy](#latestby) +- [First](#first) +- [FirstOrEmpty](#FirstOrEmpty) +- [FirstOr](#FirstOr) +- [Last](#last) +- [LastOrEmpty](#LastOrEmpty) +- [LastOr](#LastOr) +- [Nth](#nth) +- [NthOr](#nthor) +- [NthOrEmpty](#nthorempty) +- [Sample](#sample) +- [SampleBy](#sampleby) +- [Samples](#samples) +- [SamplesBy](#samplesby) + +Conditional helpers: + +- [Ternary](#ternary) +- [TernaryF](#ternaryf) +- [If / ElseIf / Else](#if--elseif--else) +- [Switch / Case / Default](#switch--case--default) + +Type manipulation helpers: + +- [IsNil](#isnil) +- [IsNotNil](#isnotnil) +- [ToPtr](#toptr) +- [Nil](#nil) +- [EmptyableToPtr](#emptyabletoptr) +- [FromPtr](#fromptr) +- [FromPtrOr](#fromptror) +- [ToSlicePtr](#tosliceptr) +- [FromSlicePtr](#fromsliceptr) +- [FromSlicePtrOr](#fromsliceptror) +- [ToAnySlice](#toanyslice) +- [FromAnySlice](#fromanyslice) +- [Empty](#empty) +- [IsEmpty](#isempty) +- [IsNotEmpty](#isnotempty) +- [Coalesce](#coalesce) +- [CoalesceOrEmpty](#coalesceorempty) +- [CoalesceSlice](#coalesceslice) +- [CoalesceSliceOrEmpty](#coalescesliceorempty) +- [CoalesceMap](#coalescemap) +- [CoalesceMapOrEmpty](#coalescemaporempty) + +Function helpers: + +- [Partial](#partial) +- [Partial2 -> Partial5](#partial2---partial5) + +Concurrency helpers: + +- [Attempt](#attempt) +- [AttemptWhile](#attemptwhile) +- [AttemptWithDelay](#attemptwithdelay) +- [AttemptWhileWithDelay](#attemptwhilewithdelay) +- [Debounce](#debounce) +- [DebounceBy](#debounceby) +- [Throttle](#throttle) +- [ThrottleWithCount](#throttle) +- [ThrottleBy](#throttle) +- [ThrottleByWithCount](#throttle) +- [Synchronize](#synchronize) +- [Async](#async) +- [Transaction](#transaction) +- [WaitFor](#waitfor) +- [WaitForWithContext](#waitforwithcontext) + +Error handling: + +- [Validate](#validate) +- [Must](#must) +- [Try](#try) +- [Try1 -> Try6](#try0-6) +- [TryOr](#tryor) +- [TryOr1 -> TryOr6](#tryor0-6) +- [TryCatch](#trycatch) +- [TryWithErrorValue](#trywitherrorvalue) +- [TryCatchWithErrorValue](#trycatchwitherrorvalue) +- [ErrorsAs](#errorsas) +- [Assert](#assert) +- [Assertf](#assertf) + +Constraints: + +- Clonable + +### Filter + +Iterates over a collection and returns an array of all the elements the predicate function returns `true` for. + +```go +even := lo.Filter([]int{1, 2, 3, 4}, func(x int, index int) bool { + return x%2 == 0 +}) +// []int{2, 4} +``` + +[[play](https://go.dev/play/p/Apjg3WeSi7K)] + +Mutable: like `lo.Filter()`, but the slice is updated in place. + +```go +import lom "github.com/samber/lo/mutable" + +list := []int{1, 2, 3, 4} +newList := lom.Filter(list, func(x int) bool { + return x%2 == 0 +}) + +list +// []int{2, 4, 3, 4} + +newList +// []int{2, 4} +``` + +### Map + +Manipulates a slice of one type and transforms it into a slice of another type: + +```go +import "github.com/samber/lo" + +lo.Map([]int64{1, 2, 3, 4}, func(x int64, index int) string { + return strconv.FormatInt(x, 10) +}) +// []string{"1", "2", "3", "4"} +``` + +[[play](https://go.dev/play/p/OkPcYAhBo0D)] + +Parallel processing: like `lo.Map()`, but the mapper function is called in a goroutine. Results are returned in the same order. + +```go +import lop "github.com/samber/lo/parallel" + +lop.Map([]int64{1, 2, 3, 4}, func(x int64, _ int) string { + return strconv.FormatInt(x, 10) +}) +// []string{"1", "2", "3", "4"} +``` + +Mutable: like `lo.Map()`, but the slice is updated in place. + +```go +import lom "github.com/samber/lo/mutable" + +list := []int{1, 2, 3, 4} +lom.Map(list, func(x int) int { + return x*2 +}) +// []int{2, 4, 6, 8} +``` + +### UniqMap + +Manipulates a slice and transforms it to a slice of another type with unique values. + +```go +type User struct { + Name string + Age int +} +users := []User{{Name: "Alex", Age: 10}, {Name: "Alex", Age: 12}, {Name: "Bob", Age: 11}, {Name: "Alice", Age: 20}} + +names := lo.UniqMap(users, func(u User, index int) string { + return u.Name +}) +// []string{"Alex", "Bob", "Alice"} +``` + +### FilterMap + +Returns a slice which obtained after both filtering and mapping using the given callback function. + +The callback function should return two values: the result of the mapping operation and whether the result element should be included or not. + +```go +matching := lo.FilterMap([]string{"cpu", "gpu", "mouse", "keyboard"}, func(x string, _ int) (string, bool) { + if strings.HasSuffix(x, "pu") { + return "xpu", true + } + return "", false +}) +// []string{"xpu", "xpu"} +``` + +[[play](https://go.dev/play/p/-AuYXfy7opz)] + +### FlatMap + +Manipulates a slice and transforms and flattens it to a slice of another type. The transform function can either return a slice or a `nil`, and in the `nil` case no value is added to the final slice. + +```go +lo.FlatMap([]int64{0, 1, 2}, func(x int64, _ int) []string { + return []string{ + strconv.FormatInt(x, 10), + strconv.FormatInt(x, 10), + } +}) +// []string{"0", "0", "1", "1", "2", "2"} +``` + +[[play](https://go.dev/play/p/YSoYmQTA8-U)] + +### Reduce + +Reduces a collection to a single value. The value is calculated by accumulating the result of running each element in the collection through an accumulator function. Each successive invocation is supplied with the return value returned by the previous call. + +```go +sum := lo.Reduce([]int{1, 2, 3, 4}, func(agg int, item int, _ int) int { + return agg + item +}, 0) +// 10 +``` + +[[play](https://go.dev/play/p/R4UHXZNaaUG)] + +### ReduceRight + +Like `lo.Reduce` except that it iterates over elements of collection from right to left. + +```go +result := lo.ReduceRight([][]int{{0, 1}, {2, 3}, {4, 5}}, func(agg []int, item []int, _ int) []int { + return append(agg, item...) +}, []int{}) +// []int{4, 5, 2, 3, 0, 1} +``` + +[[play](https://go.dev/play/p/Fq3W70l7wXF)] + +### ForEach + +Iterates over elements of a collection and invokes the function over each element. + +```go +import "github.com/samber/lo" + +lo.ForEach([]string{"hello", "world"}, func(x string, _ int) { + println(x) +}) +// prints "hello\nworld\n" +``` + +[[play](https://go.dev/play/p/oofyiUPRf8t)] + +Parallel processing: like `lo.ForEach()`, but the callback is called as a goroutine. + +```go +import lop "github.com/samber/lo/parallel" + +lop.ForEach([]string{"hello", "world"}, func(x string, _ int) { + println(x) +}) +// prints "hello\nworld\n" or "world\nhello\n" +``` + +### ForEachWhile + +Iterates over collection elements and invokes iteratee for each element collection return value decide to continue or break, like do while(). + +```go +list := []int64{1, 2, -42, 4} + +lo.ForEachWhile(list, func(x int64, _ int) bool { + if x < 0 { + return false + } + fmt.Println(x) + return true +}) +// 1 +// 2 +``` + +[[play](https://go.dev/play/p/QnLGt35tnow)] + +### Times + +Times invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with index as argument. + +```go +import "github.com/samber/lo" + +lo.Times(3, func(i int) string { + return strconv.FormatInt(int64(i), 10) +}) +// []string{"0", "1", "2"} +``` + +[[play](https://go.dev/play/p/vgQj3Glr6lT)] + +Parallel processing: like `lo.Times()`, but callback is called in goroutine. + +```go +import lop "github.com/samber/lo/parallel" + +lop.Times(3, func(i int) string { + return strconv.FormatInt(int64(i), 10) +}) +// []string{"0", "1", "2"} +``` + +### Uniq + +Returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array. + +```go +uniqValues := lo.Uniq([]int{1, 2, 2, 1}) +// []int{1, 2} +``` + +[[play](https://go.dev/play/p/DTzbeXZ6iEN)] + +### UniqBy + +Returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is invoked for each element in array to generate the criterion by which uniqueness is computed. + +```go +uniqValues := lo.UniqBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int { + return i%3 +}) +// []int{0, 1, 2} +``` + +[[play](https://go.dev/play/p/g42Z3QSb53u)] + +### GroupBy + +Returns an object composed of keys generated from the results of running each element of collection through iteratee. + +```go +import lo "github.com/samber/lo" + +groups := lo.GroupBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int { + return i%3 +}) +// map[int][]int{0: []int{0, 3}, 1: []int{1, 4}, 2: []int{2, 5}} +``` + +[[play](https://go.dev/play/p/XnQBd_v6brd)] + +Parallel processing: like `lo.GroupBy()`, but callback is called in goroutine. + +```go +import lop "github.com/samber/lo/parallel" + +lop.GroupBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int { + return i%3 +}) +// map[int][]int{0: []int{0, 3}, 1: []int{1, 4}, 2: []int{2, 5}} +``` + +### GroupByMap + +Returns an object composed of keys generated from the results of running each element of collection through iteratee. + +```go +import lo "github.com/samber/lo" + +groups := lo.GroupByMap([]int{0, 1, 2, 3, 4, 5}, func(i int) (int, int) { + return i%3, i*2 +}) +// map[int][]int{0: []int{0, 6}, 1: []int{2, 8}, 2: []int{4, 10}} +``` + +### Chunk + +Returns an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. + +```go +lo.Chunk([]int{0, 1, 2, 3, 4, 5}, 2) +// [][]int{{0, 1}, {2, 3}, {4, 5}} + +lo.Chunk([]int{0, 1, 2, 3, 4, 5, 6}, 2) +// [][]int{{0, 1}, {2, 3}, {4, 5}, {6}} + +lo.Chunk([]int{}, 2) +// [][]int{} + +lo.Chunk([]int{0}, 2) +// [][]int{{0}} +``` + +[[play](https://go.dev/play/p/EeKl0AuTehH)] + +### PartitionBy + +Returns an array of elements split into groups. The order of grouped values is determined by the order they occur in collection. The grouping is generated from the results of running each element of collection through iteratee. + +```go +import lo "github.com/samber/lo" + +partitions := lo.PartitionBy([]int{-2, -1, 0, 1, 2, 3, 4, 5}, func(x int) string { + if x < 0 { + return "negative" + } else if x%2 == 0 { + return "even" + } + return "odd" +}) +// [][]int{{-2, -1}, {0, 2, 4}, {1, 3, 5}} +``` + +[[play](https://go.dev/play/p/NfQ_nGjkgXW)] + +Parallel processing: like `lo.PartitionBy()`, but callback is called in goroutine. Results are returned in the same order. + +```go +import lop "github.com/samber/lo/parallel" + +partitions := lop.PartitionBy([]int{-2, -1, 0, 1, 2, 3, 4, 5}, func(x int) string { + if x < 0 { + return "negative" + } else if x%2 == 0 { + return "even" + } + return "odd" +}) +// [][]int{{-2, -1}, {0, 2, 4}, {1, 3, 5}} +``` + +### Flatten + +Returns an array a single level deep. + +```go +flat := lo.Flatten([][]int{{0, 1}, {2, 3, 4, 5}}) +// []int{0, 1, 2, 3, 4, 5} +``` + +[[play](https://go.dev/play/p/rbp9ORaMpjw)] + +### Interleave + +Round-robin alternating input slices and sequentially appending value at index into result. + +```go +interleaved := lo.Interleave([]int{1, 4, 7}, []int{2, 5, 8}, []int{3, 6, 9}) +// []int{1, 2, 3, 4, 5, 6, 7, 8, 9} + +interleaved := lo.Interleave([]int{1}, []int{2, 5, 8}, []int{3, 6}, []int{4, 7, 9, 10}) +// []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +``` + +[[play](https://go.dev/play/p/-RJkTLQEDVt)] + +### Shuffle + +Returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm. + +⚠️ This helper is **mutable**. + +```go +import lom "github.com/samber/lo/mutable" + +list := []int{0, 1, 2, 3, 4, 5} +lom.Shuffle(list) + +list +// []int{1, 4, 0, 3, 5, 2} +``` + +[[play](https://go.dev/play/p/2xb3WdLjeSJ)] + +### Reverse + +Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on. + +⚠️ This helper is **mutable**. + +```go +import lom "github.com/samber/lo/mutable" + +list := []int{0, 1, 2, 3, 4, 5} +lom.Reverse(list) + +list +// []int{5, 4, 3, 2, 1, 0} +``` + +[[play](https://go.dev/play/p/O-M5pmCRgzV)] + +### Fill + +Fills elements of array with `initial` value. + +```go +type foo struct { + bar string +} + +func (f foo) Clone() foo { + return foo{f.bar} +} + +initializedSlice := lo.Fill([]foo{foo{"a"}, foo{"a"}}, foo{"b"}) +// []foo{foo{"b"}, foo{"b"}} +``` + +[[play](https://go.dev/play/p/VwR34GzqEub)] + +### Repeat + +Builds a slice with N copies of initial value. + +```go +type foo struct { + bar string +} + +func (f foo) Clone() foo { + return foo{f.bar} +} + +slice := lo.Repeat(2, foo{"a"}) +// []foo{foo{"a"}, foo{"a"}} +``` + +[[play](https://go.dev/play/p/g3uHXbmc3b6)] + +### RepeatBy + +Builds a slice with values returned by N calls of callback. + +```go +slice := lo.RepeatBy(0, func (i int) string { + return strconv.FormatInt(int64(math.Pow(float64(i), 2)), 10) +}) +// []string{} + +slice := lo.RepeatBy(5, func(i int) string { + return strconv.FormatInt(int64(math.Pow(float64(i), 2)), 10) +}) +// []string{"0", "1", "4", "9", "16"} +``` + +[[play](https://go.dev/play/p/ozZLCtX_hNU)] + +### KeyBy + +Transforms a slice or an array of structs to a map based on a pivot callback. + +```go +m := lo.KeyBy([]string{"a", "aa", "aaa"}, func(str string) int { + return len(str) +}) +// map[int]string{1: "a", 2: "aa", 3: "aaa"} + +type Character struct { + dir string + code int +} +characters := []Character{ + {dir: "left", code: 97}, + {dir: "right", code: 100}, +} +result := lo.KeyBy(characters, func(char Character) string { + return string(rune(char.code)) +}) +//map[a:{dir:left code:97} d:{dir:right code:100}] +``` + +[[play](https://go.dev/play/p/mdaClUAT-zZ)] + +### SliceToMap (alias: Associate) + +Returns a map containing key-value pairs provided by transform function applied to elements of the given slice. +If any of two pairs would have the same key the last one gets added to the map. + +The order of keys in returned map is not specified and is not guaranteed to be the same from the original array. + +```go +in := []*foo{{baz: "apple", bar: 1}, {baz: "banana", bar: 2}} + +aMap := lo.SliceToMap(in, func (f *foo) (string, int) { + return f.baz, f.bar +}) +// map[string][int]{ "apple":1, "banana":2 } +``` + +[[play](https://go.dev/play/p/WHa2CfMO3Lr)] + +### FilterSliceToMap + +Returns a map containing key-value pairs provided by transform function applied to elements of the given slice. + +If any of two pairs would have the same key the last one gets added to the map. + +The order of keys in returned map is not specified and is not guaranteed to be the same from the original array. + +The third return value of the transform function is a boolean that indicates whether the key-value pair should be included in the map. + + +```go +list := []string{"a", "aa", "aaa"} + +result := lo.FilterSliceToMap(list, func(str string) (string, int, bool) { + return str, len(str), len(str) > 1 +}) +// map[string][int]{"aa":2 "aaa":3} +``` + +### Keyify + +Returns a map with each unique element of the slice as a key. + +```go +set := lo.Keyify([]int{1, 1, 2, 3, 4}) +// map[int]struct{}{1:{}, 2:{}, 3:{}, 4:{}} +``` + +### Drop + +Drops n elements from the beginning of a slice or array. + +```go +l := lo.Drop([]int{0, 1, 2, 3, 4, 5}, 2) +// []int{2, 3, 4, 5} +``` + +[[play](https://go.dev/play/p/JswS7vXRJP2)] + +### DropRight + +Drops n elements from the end of a slice or array. + +```go +l := lo.DropRight([]int{0, 1, 2, 3, 4, 5}, 2) +// []int{0, 1, 2, 3} +``` + +[[play](https://go.dev/play/p/GG0nXkSJJa3)] + +### DropWhile + +Drop elements from the beginning of a slice or array while the predicate returns true. + +```go +l := lo.DropWhile([]string{"a", "aa", "aaa", "aa", "aa"}, func(val string) bool { + return len(val) <= 2 +}) +// []string{"aaa", "aa", "aa"} +``` + +[[play](https://go.dev/play/p/7gBPYw2IK16)] + +### DropRightWhile + +Drop elements from the end of a slice or array while the predicate returns true. + +```go +l := lo.DropRightWhile([]string{"a", "aa", "aaa", "aa", "aa"}, func(val string) bool { + return len(val) <= 2 +}) +// []string{"a", "aa", "aaa"} +``` + +[[play](https://go.dev/play/p/3-n71oEC0Hz)] + +### DropByIndex + +Drops elements from a slice or array by the index. A negative index will drop elements from the end of the slice. + +```go +l := lo.DropByIndex([]int{0, 1, 2, 3, 4, 5}, 2, 4, -1) +// []int{0, 1, 3} +``` + +[[play](https://go.dev/play/p/JswS7vXRJP2)] + +### Reject + +The opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. + +```go +odd := lo.Reject([]int{1, 2, 3, 4}, func(x int, _ int) bool { + return x%2 == 0 +}) +// []int{1, 3} +``` + +[[play](https://go.dev/play/p/YkLMODy1WEL)] + +### RejectMap + +The opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. + +The callback function should return two values: + +- the result of the mapping operation and +- whether the result element should be included or not. + +```go +items := lo.RejectMap([]int{1, 2, 3, 4}, func(x int, _ int) (int, bool) { + return x*10, x%2 == 0 +}) +// []int{10, 30} +``` + +### FilterReject + +Mixes Filter and Reject, this method returns two slices, one for the elements of collection that predicate returns truthy for and one for the elements that predicate does not return truthy for. + +```go +kept, rejected := lo.FilterReject([]int{1, 2, 3, 4}, func(x int, _ int) bool { + return x%2 == 0 +}) +// []int{2, 4} +// []int{1, 3} +``` + +### Count + +Counts the number of elements in the collection that compare equal to value. + +```go +count := lo.Count([]int{1, 5, 1}, 1) +// 2 +``` + +[[play](https://go.dev/play/p/Y3FlK54yveC)] + +### CountBy + +Counts the number of elements in the collection for which predicate is true. + +```go +count := lo.CountBy([]int{1, 5, 1}, func(i int) bool { + return i < 4 +}) +// 2 +``` + +[[play](https://go.dev/play/p/ByQbNYQQi4X)] + +### CountValues + +Counts the number of each element in the collection. + +```go +lo.CountValues([]int{}) +// map[int]int{} + +lo.CountValues([]int{1, 2}) +// map[int]int{1: 1, 2: 1} + +lo.CountValues([]int{1, 2, 2}) +// map[int]int{1: 1, 2: 2} + +lo.CountValues([]string{"foo", "bar", ""}) +// map[string]int{"": 1, "foo": 1, "bar": 1} + +lo.CountValues([]string{"foo", "bar", "bar"}) +// map[string]int{"foo": 1, "bar": 2} +``` + +[[play](https://go.dev/play/p/-p-PyLT4dfy)] + +### CountValuesBy + +Counts the number of each element in the collection. It ss equivalent to chaining lo.Map and lo.CountValues. + +```go +isEven := func(v int) bool { + return v%2==0 +} + +lo.CountValuesBy([]int{}, isEven) +// map[bool]int{} + +lo.CountValuesBy([]int{1, 2}, isEven) +// map[bool]int{false: 1, true: 1} + +lo.CountValuesBy([]int{1, 2, 2}, isEven) +// map[bool]int{false: 1, true: 2} + +length := func(v string) int { + return len(v) +} + +lo.CountValuesBy([]string{"foo", "bar", ""}, length) +// map[int]int{0: 1, 3: 2} + +lo.CountValuesBy([]string{"foo", "bar", "bar"}, length) +// map[int]int{3: 3} +``` + +[[play](https://go.dev/play/p/2U0dG1SnOmS)] + +### Subset + +Returns a copy of a slice from `offset` up to `length` elements. Like `slice[start:start+length]`, but does not panic on overflow. + +```go +in := []int{0, 1, 2, 3, 4} + +sub := lo.Subset(in, 2, 3) +// []int{2, 3, 4} + +sub := lo.Subset(in, -4, 3) +// []int{1, 2, 3} + +sub := lo.Subset(in, -2, math.MaxUint) +// []int{3, 4} +``` + +[[play](https://go.dev/play/p/tOQu1GhFcog)] + +### Slice + +Returns a copy of a slice from `start` up to, but not including `end`. Like `slice[start:end]`, but does not panic on overflow. + +```go +in := []int{0, 1, 2, 3, 4} + +slice := lo.Slice(in, 0, 5) +// []int{0, 1, 2, 3, 4} + +slice := lo.Slice(in, 2, 3) +// []int{2} + +slice := lo.Slice(in, 2, 6) +// []int{2, 3, 4} + +slice := lo.Slice(in, 4, 3) +// []int{} +``` + +[[play](https://go.dev/play/p/8XWYhfMMA1h)] + +### Replace + +Returns a copy of the slice with the first n non-overlapping instances of old replaced by new. + +```go +in := []int{0, 1, 0, 1, 2, 3, 0} + +slice := lo.Replace(in, 0, 42, 1) +// []int{42, 1, 0, 1, 2, 3, 0} + +slice := lo.Replace(in, -1, 42, 1) +// []int{0, 1, 0, 1, 2, 3, 0} + +slice := lo.Replace(in, 0, 42, 2) +// []int{42, 1, 42, 1, 2, 3, 0} + +slice := lo.Replace(in, 0, 42, -1) +// []int{42, 1, 42, 1, 2, 3, 42} +``` + +[[play](https://go.dev/play/p/XfPzmf9gql6)] + +### ReplaceAll + +Returns a copy of the slice with all non-overlapping instances of old replaced by new. + +```go +in := []int{0, 1, 0, 1, 2, 3, 0} + +slice := lo.ReplaceAll(in, 0, 42) +// []int{42, 1, 42, 1, 2, 3, 42} + +slice := lo.ReplaceAll(in, -1, 42) +// []int{0, 1, 0, 1, 2, 3, 0} +``` + +[[play](https://go.dev/play/p/a9xZFUHfYcV)] + +### Compact + +Returns a slice of all non-zero elements. + +```go +in := []string{"", "foo", "", "bar", ""} + +slice := lo.Compact(in) +// []string{"foo", "bar"} +``` + +[[play](https://go.dev/play/p/tXiy-iK6PAc)] + +### IsSorted + +Checks if a slice is sorted. + +```go +slice := lo.IsSorted([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) +// true +``` + +[[play](https://go.dev/play/p/mc3qR-t4mcx)] + +### IsSortedByKey + +Checks if a slice is sorted by iteratee. + +```go +slice := lo.IsSortedByKey([]string{"a", "bb", "ccc"}, func(s string) int { + return len(s) +}) +// true +``` + +[[play](https://go.dev/play/p/wiG6XyBBu49)] + +### Splice + +Splice inserts multiple elements at index i. A negative index counts back from the end of the slice. The helper is protected against overflow errors. + +```go +result := lo.Splice([]string{"a", "b"}, 1, "1", "2") +// []string{"a", "1", "2", "b"} + +// negative +result = lo.Splice([]string{"a", "b"}, -1, "1", "2") +// []string{"a", "1", "2", "b"} + +// overflow +result = lo.Splice([]string{"a", "b"}, 42, "1", "2") +// []string{"a", "b", "1", "2"} +``` + +[[play](https://go.dev/play/p/wiG6XyBBu49)] + +### Keys + +Creates a slice of the map keys. + +Use the UniqKeys variant to deduplicate common keys. + +```go +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}) +// []string{"foo", "bar"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar", "bar"} +``` + +[[play](https://go.dev/play/p/Uu11fHASqrU)] + +### UniqKeys + +Creates an array of unique map keys. + +```go +keys := lo.UniqKeys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.UniqKeys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar"} +``` + +[[play](https://go.dev/play/p/TPKAb6ILdHk)] + +### HasKey + +Returns whether the given key exists. + +```go +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "foo") +// true + +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "baz") +// false +``` + +[[play](https://go.dev/play/p/aVwubIvECqS)] + +### Values + +Creates an array of the map values. + +Use the UniqValues variant to deduplicate common values. + +```go +values := lo.Values(map[string]int{"foo": 1, "bar": 2}) +// []int{1, 2} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2, 2} +``` + +[[play](https://go.dev/play/p/nnRTQkzQfF6)] + +### UniqValues + +Creates an array of unique map values. + +```go +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}) +// []int{1, 2} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2} +``` + +[[play](https://go.dev/play/p/nf6bXMh7rM3)] + +### ValueOr + +Returns the value of the given key or the fallback value if the key is not present. + +```go +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "foo", 42) +// 1 + +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "baz", 42) +// 42 +``` + +[[play](https://go.dev/play/p/bAq9mHErB4V)] + +### PickBy + +Returns same map type filtered by given predicate. + +```go +m := lo.PickBy(map[string]int{"foo": 1, "bar": 2, "baz": 3}, func(key string, value int) bool { + return value%2 == 1 +}) +// map[string]int{"foo": 1, "baz": 3} +``` + +[[play](https://go.dev/play/p/kdg8GR_QMmf)] + +### PickByKeys + +Returns same map type filtered by given keys. + +```go +m := lo.PickByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"}) +// map[string]int{"foo": 1, "baz": 3} +``` + +[[play](https://go.dev/play/p/R1imbuci9qU)] + +### PickByValues + +Returns same map type filtered by given values. + +```go +m := lo.PickByValues(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []int{1, 3}) +// map[string]int{"foo": 1, "baz": 3} +``` + +[[play](https://go.dev/play/p/1zdzSvbfsJc)] + +### OmitBy + +Returns same map type filtered by given predicate. + +```go +m := lo.OmitBy(map[string]int{"foo": 1, "bar": 2, "baz": 3}, func(key string, value int) bool { + return value%2 == 1 +}) +// map[string]int{"bar": 2} +``` + +[[play](https://go.dev/play/p/EtBsR43bdsd)] + +### OmitByKeys + +Returns same map type filtered by given keys. + +```go +m := lo.OmitByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"}) +// map[string]int{"bar": 2} +``` + +[[play](https://go.dev/play/p/t1QjCrs-ysk)] + +### OmitByValues + +Returns same map type filtered by given values. + +```go +m := lo.OmitByValues(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []int{1, 3}) +// map[string]int{"bar": 2} +``` + +[[play](https://go.dev/play/p/9UYZi-hrs8j)] + +### Entries (alias: ToPairs) + +Transforms a map into array of key/value pairs. + +```go +entries := lo.Entries(map[string]int{"foo": 1, "bar": 2}) +// []lo.Entry[string, int]{ +// { +// Key: "foo", +// Value: 1, +// }, +// { +// Key: "bar", +// Value: 2, +// }, +// } +``` + +[[play](https://go.dev/play/p/3Dhgx46gawJ)] + +### FromEntries (alias: FromPairs) + +Transforms an array of key/value pairs into a map. + +```go +m := lo.FromEntries([]lo.Entry[string, int]{ + { + Key: "foo", + Value: 1, + }, + { + Key: "bar", + Value: 2, + }, +}) +// map[string]int{"foo": 1, "bar": 2} +``` + +[[play](https://go.dev/play/p/oIr5KHFGCEN)] + +### Invert + +Creates a map composed of the inverted keys and values. If map contains duplicate values, subsequent values overwrite property assignments of previous values. + +```go +m1 := lo.Invert(map[string]int{"a": 1, "b": 2}) +// map[int]string{1: "a", 2: "b"} + +m2 := lo.Invert(map[string]int{"a": 1, "b": 2, "c": 1}) +// map[int]string{1: "c", 2: "b"} +``` + +[[play](https://go.dev/play/p/rFQ4rak6iA1)] + +### Assign + +Merges multiple maps from left to right. + +```go +mergedMaps := lo.Assign( + map[string]int{"a": 1, "b": 2}, + map[string]int{"b": 3, "c": 4}, +) +// map[string]int{"a": 1, "b": 3, "c": 4} +``` + +[[play](https://go.dev/play/p/VhwfJOyxf5o)] + +### ChunkEntries + +Splits a map into an array of elements in groups of a length equal to its size. If the map cannot be split evenly, the final chunk will contain the remaining elements. + +```go +maps := lo.ChunkEntries( + map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + }, + 3, +) +// []map[string]int{ +// {"a": 1, "b": 2, "c": 3}, +// {"d": 4, "e": 5}, +// } +``` +[[play](https://go.dev/play/p/X_YQL6mmoD-)] + +### MapKeys + +Manipulates a map keys and transforms it to a map of another type. + +```go +m2 := lo.MapKeys(map[int]int{1: 1, 2: 2, 3: 3, 4: 4}, func(_ int, v int) string { + return strconv.FormatInt(int64(v), 10) +}) +// map[string]int{"1": 1, "2": 2, "3": 3, "4": 4} +``` + +[[play](https://go.dev/play/p/9_4WPIqOetJ)] + +### MapValues + +Manipulates a map values and transforms it to a map of another type. + +```go +m1 := map[int]int64{1: 1, 2: 2, 3: 3} + +m2 := lo.MapValues(m1, func(x int64, _ int) string { + return strconv.FormatInt(x, 10) +}) +// map[int]string{1: "1", 2: "2", 3: "3"} +``` + +[[play](https://go.dev/play/p/T_8xAfvcf0W)] + +### MapEntries + +Manipulates a map entries and transforms it to a map of another type. + +```go +in := map[string]int{"foo": 1, "bar": 2} + +out := lo.MapEntries(in, func(k string, v int) (int, string) { + return v,k +}) +// map[int]string{1: "foo", 2: "bar"} +``` + +[[play](https://go.dev/play/p/VuvNQzxKimT)] + +### MapToSlice + +Transforms a map into a slice based on specific iteratee. + +```go +m := map[int]int64{1: 4, 2: 5, 3: 6} + +s := lo.MapToSlice(m, func(k int, v int64) string { + return fmt.Sprintf("%d_%d", k, v) +}) +// []string{"1_4", "2_5", "3_6"} +``` + +[[play](https://go.dev/play/p/ZuiCZpDt6LD)] + +### FilterMapToSlice + +Transforms a map into a slice based on specific iteratee. The iteratee returns a value and a boolean. If the boolean is true, the value is added to the result slice. + +If the boolean is false, the value is not added to the result slice. The order of the keys in the input map is not specified and the order of the keys in the output slice is not guaranteed. + +```go +kv := map[int]int64{1: 1, 2: 2, 3: 3, 4: 4} + +result := lo.FilterMapToSlice(kv, func(k int, v int64) (string, bool) { + return fmt.Sprintf("%d_%d", k, v), k%2 == 0 +}) +// []{"2_2", "4_4"} +``` + +### Range / RangeFrom / RangeWithSteps + +Creates an array of numbers (positive and/or negative) progressing from start up to, but not including end. + +```go +result := lo.Range(4) +// [0, 1, 2, 3] + +result := lo.Range(-4) +// [0, -1, -2, -3] + +result := lo.RangeFrom(1, 5) +// [1, 2, 3, 4, 5] + +result := lo.RangeFrom[float64](1.0, 5) +// [1.0, 2.0, 3.0, 4.0, 5.0] + +result := lo.RangeWithSteps(0, 20, 5) +// [0, 5, 10, 15] + +result := lo.RangeWithSteps[float32](-1.0, -4.0, -1.0) +// [-1.0, -2.0, -3.0] + +result := lo.RangeWithSteps(1, 4, -1) +// [] + +result := lo.Range(0) +// [] +``` + +[[play](https://go.dev/play/p/0r6VimXAi9H)] + +### Clamp + +Clamps number within the inclusive lower and upper bounds. + +```go +r1 := lo.Clamp(0, -10, 10) +// 0 + +r2 := lo.Clamp(-42, -10, 10) +// -10 + +r3 := lo.Clamp(42, -10, 10) +// 10 +``` + +[[play](https://go.dev/play/p/RU4lJNC2hlI)] + +### Sum + +Sums the values in a collection. + +If collection is empty 0 is returned. + +```go +list := []int{1, 2, 3, 4, 5} +sum := lo.Sum(list) +// 15 +``` + +[[play](https://go.dev/play/p/upfeJVqs4Bt)] + +### SumBy + +Summarizes the values in a collection using the given return value from the iteration function. + +If collection is empty 0 is returned. + +```go +strings := []string{"foo", "bar"} +sum := lo.SumBy(strings, func(item string) int { + return len(item) +}) +// 6 +``` + +### Product + +Calculates the product of the values in a collection. + +If collection is empty 0 is returned. + +```go +list := []int{1, 2, 3, 4, 5} +product := lo.Product(list) +// 120 +``` + +[[play](https://go.dev/play/p/2_kjM_smtAH)] + +### ProductBy + +Calculates the product of the values in a collection using the given return value from the iteration function. + +If collection is empty 0 is returned. + +```go +strings := []string{"foo", "bar"} +product := lo.ProductBy(strings, func(item string) int { + return len(item) +}) +// 9 +``` + +[[play](https://go.dev/play/p/wadzrWr9Aer)] + +### Mean + +Calculates the mean of a collection of numbers. + +If collection is empty 0 is returned. + +```go +mean := lo.Mean([]int{2, 3, 4, 5}) +// 3 + +mean := lo.Mean([]float64{2, 3, 4, 5}) +// 3.5 + +mean := lo.Mean([]float64{}) +// 0 +``` + +### MeanBy + +Calculates the mean of a collection of numbers using the given return value from the iteration function. + +If collection is empty 0 is returned. + +```go +list := []string{"aa", "bbb", "cccc", "ddddd"} +mapper := func(item string) float64 { + return float64(len(item)) +} + +mean := lo.MeanBy(list, mapper) +// 3.5 + +mean := lo.MeanBy([]float64{}, mapper) +// 0 +``` + +### RandomString + +Returns a random string of the specified length and made of the specified charset. + +```go +str := lo.RandomString(5, lo.LettersCharset) +// example: "eIGbt" +``` + +[[play](https://go.dev/play/p/rRseOQVVum4)] + +### Substring + +Return part of a string. + +```go +sub := lo.Substring("hello", 2, 3) +// "llo" + +sub := lo.Substring("hello", -4, 3) +// "ell" + +sub := lo.Substring("hello", -2, math.MaxUint) +// "lo" +``` + +[[play](https://go.dev/play/p/TQlxQi82Lu1)] + +### ChunkString + +Returns an array of strings split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. + +```go +lo.ChunkString("123456", 2) +// []string{"12", "34", "56"} + +lo.ChunkString("1234567", 2) +// []string{"12", "34", "56", "7"} + +lo.ChunkString("", 2) +// []string{""} + +lo.ChunkString("1", 2) +// []string{"1"} +``` + +[[play](https://go.dev/play/p/__FLTuJVz54)] + +### RuneLength + +An alias to utf8.RuneCountInString which returns the number of runes in string. + +```go +sub := lo.RuneLength("hellô") +// 5 + +sub := len("hellô") +// 6 +``` + +[[play](https://go.dev/play/p/tuhgW_lWY8l)] + +### PascalCase + +Converts string to pascal case. + +```go +str := lo.PascalCase("hello_world") +// HelloWorld +``` + +[[play](https://go.dev/play/p/iZkdeLP9oiB)] + +### CamelCase + +Converts string to camel case. + +```go +str := lo.CamelCase("hello_world") +// helloWorld +``` + +[[play](https://go.dev/play/p/dtyFB58MBRp)] + +### KebabCase + +Converts string to kebab case. + +```go +str := lo.KebabCase("helloWorld") +// hello-world +``` + +[[play](https://go.dev/play/p/2YTuPafwECA)] + +### SnakeCase + +Converts string to snake case. + +```go +str := lo.SnakeCase("HelloWorld") +// hello_world +``` + +[[play](https://go.dev/play/p/QVKJG9nOnDg)] + +### Words + +Splits string into an array of its words. + +```go +str := lo.Words("helloWorld") +// []string{"hello", "world"} +``` + +[[play](https://go.dev/play/p/2P4zhqqq61g)] + +### Capitalize + +Converts the first character of string to upper case and the remaining to lower case. + +```go +str := lo.Capitalize("heLLO") +// Hello +``` + +### Ellipsis + +Trims and truncates a string to a specified length **in bytes** and appends an ellipsis if truncated. If the string contains non-ASCII characters (which may occupy multiple bytes in UTF-8), truncating by byte length may split a character in the middle, potentially resulting in garbled output. + +```go +str := lo.Ellipsis(" Lorem Ipsum ", 5) +// Lo... + +str := lo.Ellipsis("Lorem Ipsum", 100) +// Lorem Ipsum + +str := lo.Ellipsis("Lorem Ipsum", 3) +// ... +``` + +### T2 -> T9 + +Creates a tuple from a list of values. + +```go +tuple1 := lo.T2("x", 1) +// Tuple2[string, int]{A: "x", B: 1} + +func example() (string, int) { return "y", 2 } +tuple2 := lo.T2(example()) +// Tuple2[string, int]{A: "y", B: 2} +``` + +[[play](https://go.dev/play/p/IllL3ZO4BQm)] + +### Unpack2 -> Unpack9 + +Returns values contained in tuple. + +```go +r1, r2 := lo.Unpack2(lo.Tuple2[string, int]{"a", 1}) +// "a", 1 +``` + +Unpack is also available as a method of TupleX. + +```go +tuple2 := lo.T2("a", 1) +a, b := tuple2.Unpack() +// "a", 1 +``` + +[[play](https://go.dev/play/p/xVP_k0kJ96W)] + +### Zip2 -> Zip9 + +Zip creates a slice of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on. + +When collections have different size, the Tuple attributes are filled with zero value. + +```go +tuples := lo.Zip2([]string{"a", "b"}, []int{1, 2}) +// []Tuple2[string, int]{{A: "a", B: 1}, {A: "b", B: 2}} +``` + +[[play](https://go.dev/play/p/jujaA6GaJTp)] + +### ZipBy2 -> ZipBy9 + +ZipBy creates a slice of transformed elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on. + +When collections have different size, the Tuple attributes are filled with zero value. + +```go +items := lo.ZipBy2([]string{"a", "b"}, []int{1, 2}, func(a string, b int) string { + return fmt.Sprintf("%s-%d", a, b) +}) +// []string{"a-1", "b-2"} +``` + +### Unzip2 -> Unzip9 + +Unzip accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration. + +```go +a, b := lo.Unzip2([]Tuple2[string, int]{{A: "a", B: 1}, {A: "b", B: 2}}) +// []string{"a", "b"} +// []int{1, 2} +``` + +[[play](https://go.dev/play/p/ciHugugvaAW)] + +### UnzipBy2 -> UnzipBy9 + +UnzipBy2 iterates over a collection and creates an array regrouping the elements to their pre-zip configuration. + +```go +a, b := lo.UnzipBy2([]string{"hello", "john", "doe"}, func(str string) (string, int) { + return str, len(str) +}) +// []string{"hello", "john", "doe"} +// []int{5, 4, 3} +``` + +### CrossJoin2 -> CrossJoin9 + +Combines every items from one list with every items from others. It is the cartesian product of lists received as arguments. It returns an empty list if a list is empty. + +```go +result := lo.CrossJoin2([]string{"hello", "john", "doe"}, []int{1, 2}) +// lo.Tuple2{"hello", 1} +// lo.Tuple2{"hello", 2} +// lo.Tuple2{"john", 1} +// lo.Tuple2{"john", 2} +// lo.Tuple2{"doe", 1} +// lo.Tuple2{"doe", 2} +``` + +### CrossJoinBy2 -> CrossJoinBy9 + +Combines every items from one list with every items from others. It is the cartesian product of lists received as arguments. The project function is used to create the output values. It returns an empty list if a list is empty. + +```go +result := lo.CrossJoinBy2([]string{"hello", "john", "doe"}, []int{1, 2}, func(a A, b B) string { + return fmt.Sprintf("%s - %d", a, b) +}) +// "hello - 1" +// "hello - 2" +// "john - 1" +// "john - 2" +// "doe - 1" +// "doe - 2" +``` + +### Duration + +Returns the time taken to execute a function. + +```go +duration := lo.Duration(func() { + // very long job +}) +// 3s +``` + +### Duration0 -> Duration10 + +Returns the time taken to execute a function. + +```go +duration := lo.Duration0(func() { + // very long job +}) +// 3s + +err, duration := lo.Duration1(func() error { + // very long job + return fmt.Errorf("an error") +}) +// an error +// 3s + +str, nbr, err, duration := lo.Duration3(func() (string, int, error) { + // very long job + return "hello", 42, nil +}) +// hello +// 42 +// nil +// 3s +``` + +### ChannelDispatcher + +Distributes messages from input channels into N child channels. Close events are propagated to children. + +Underlying channels can have a fixed buffer capacity or be unbuffered when cap is 0. + +```go +ch := make(chan int, 42) +for i := 0; i <= 10; i++ { + ch <- i +} + +children := lo.ChannelDispatcher(ch, 5, 10, DispatchingStrategyRoundRobin[int]) +// []<-chan int{...} + +consumer := func(c <-chan int) { + for { + msg, ok := <-c + if !ok { + println("closed") + + break + } + + println(msg) + } +} + +for i := range children { + go consumer(children[i]) +} +``` + +Many distributions strategies are available: + +- [lo.DispatchingStrategyRoundRobin](./channel.go): Distributes messages in a rotating sequential manner. +- [lo.DispatchingStrategyRandom](./channel.go): Distributes messages in a random manner. +- [lo.DispatchingStrategyWeightedRandom](./channel.go): Distributes messages in a weighted manner. +- [lo.DispatchingStrategyFirst](./channel.go): Distributes messages in the first non-full channel. +- [lo.DispatchingStrategyLeast](./channel.go): Distributes messages in the emptiest channel. +- [lo.DispatchingStrategyMost](./channel.go): Distributes to the fullest channel. + +Some strategies bring fallback, in order to favor non-blocking behaviors. See implementations. + +For custom strategies, just implement the `lo.DispatchingStrategy` prototype: + +```go +type DispatchingStrategy[T any] func(message T, messageIndex uint64, channels []<-chan T) int +``` + +Eg: + +```go +type Message struct { + TenantID uuid.UUID +} + +func hash(id uuid.UUID) int { + h := fnv.New32a() + h.Write([]byte(id.String())) + return int(h.Sum32()) +} + +// Routes messages per TenantID. +customStrategy := func(message string, messageIndex uint64, channels []<-chan string) int { + destination := hash(message) % len(channels) + + // check if channel is full + if len(channels[destination]) < cap(channels[destination]) { + return destination + } + + // fallback when child channel is full + return utils.DispatchingStrategyRoundRobin(message, uint64(destination), channels) +} + +children := lo.ChannelDispatcher(ch, 5, 10, customStrategy) +... +``` + +### SliceToChannel + +Returns a read-only channels of collection elements. Channel is closed after last element. Channel capacity can be customized. + +```go +list := []int{1, 2, 3, 4, 5} + +for v := range lo.SliceToChannel(2, list) { + println(v) +} +// prints 1, then 2, then 3, then 4, then 5 +``` + +### ChannelToSlice + +Returns a slice built from channels items. Blocks until channel closes. + +```go +list := []int{1, 2, 3, 4, 5} +ch := lo.SliceToChannel(2, list) + +items := ChannelToSlice(ch) +// []int{1, 2, 3, 4, 5} +``` + +### Generator + +Implements the generator design pattern. Channel is closed after last element. Channel capacity can be customized. + +```go +generator := func(yield func(int)) { + yield(1) + yield(2) + yield(3) +} + +for v := range lo.Generator(2, generator) { + println(v) +} +// prints 1, then 2, then 3 +``` + +### Buffer + +Creates a slice of n elements from a channel. Returns the slice, the slice length, the read time and the channel status (opened/closed). + +```go +ch := lo.SliceToChannel(2, []int{1, 2, 3, 4, 5}) + +items1, length1, duration1, ok1 := lo.Buffer(ch, 3) +// []int{1, 2, 3}, 3, 0s, true +items2, length2, duration2, ok2 := lo.Buffer(ch, 3) +// []int{4, 5}, 2, 0s, false +``` + +Example: RabbitMQ consumer 👇 + +```go +ch := readFromQueue() + +for { + // read 1k items + items, length, _, ok := lo.Buffer(ch, 1000) + + // do batching stuff + + if !ok { + break + } +} +``` + +### BufferWithContext + +Creates a slice of n elements from a channel, with timeout. Returns the slice, the slice length, the read time and the channel status (opened/closed). + +```go +ctx, cancel := context.WithCancel(context.TODO()) +go func() { + ch <- 0 + time.Sleep(10*time.Millisecond) + ch <- 1 + time.Sleep(10*time.Millisecond) + ch <- 2 + time.Sleep(10*time.Millisecond) + ch <- 3 + time.Sleep(10*time.Millisecond) + ch <- 4 + time.Sleep(10*time.Millisecond) + cancel() +}() + +items1, length1, duration1, ok1 := lo.BufferWithContext(ctx, ch, 3) +// []int{0, 1, 2}, 3, 20ms, true +items2, length2, duration2, ok2 := lo.BufferWithContext(ctx, ch, 3) +// []int{3, 4}, 2, 30ms, false +``` + +### BufferWithTimeout + +Creates a slice of n elements from a channel, with timeout. Returns the slice, the slice length, the read time and the channel status (opened/closed). + +```go +generator := func(yield func(int)) { + for i := 0; i < 5; i++ { + yield(i) + time.Sleep(35*time.Millisecond) + } +} + +ch := lo.Generator(0, generator) + +items1, length1, duration1, ok1 := lo.BufferWithTimeout(ch, 3, 100*time.Millisecond) +// []int{1, 2}, 2, 100ms, true +items2, length2, duration2, ok2 := lo.BufferWithTimeout(ch, 3, 100*time.Millisecond) +// []int{3, 4, 5}, 3, 75ms, true +items3, length3, duration2, ok3 := lo.BufferWithTimeout(ch, 3, 100*time.Millisecond) +// []int{}, 0, 10ms, false +``` + +Example: RabbitMQ consumer 👇 + +```go +ch := readFromQueue() + +for { + // read 1k items + // wait up to 1 second + items, length, _, ok := lo.BufferWithTimeout(ch, 1000, 1*time.Second) + + // do batching stuff + + if !ok { + break + } +} +``` + +Example: Multithreaded RabbitMQ consumer 👇 + +```go +ch := readFromQueue() + +// 5 workers +// prefetch 1k messages per worker +children := lo.ChannelDispatcher(ch, 5, 1000, lo.DispatchingStrategyFirst[int]) + +consumer := func(c <-chan int) { + for { + // read 1k items + // wait up to 1 second + items, length, _, ok := lo.BufferWithTimeout(ch, 1000, 1*time.Second) + + // do batching stuff + + if !ok { + break + } + } +} + +for i := range children { + go consumer(children[i]) +} +``` + +### FanIn + +Merge messages from multiple input channels into a single buffered channel. Output messages has no priority. When all upstream channels reach EOF, downstream channel closes. + +```go +stream1 := make(chan int, 42) +stream2 := make(chan int, 42) +stream3 := make(chan int, 42) + +all := lo.FanIn(100, stream1, stream2, stream3) +// <-chan int +``` + +### FanOut + +Broadcasts all the upstream messages to multiple downstream channels. When upstream channel reach EOF, downstream channels close. If any downstream channels is full, broadcasting is paused. + +```go +stream := make(chan int, 42) + +all := lo.FanOut(5, 100, stream) +// [5]<-chan int +``` + +### Contains + +Returns true if an element is present in a collection. + +```go +present := lo.Contains([]int{0, 1, 2, 3, 4, 5}, 5) +// true +``` + +### ContainsBy + +Returns true if the predicate function returns `true`. + +```go +present := lo.ContainsBy([]int{0, 1, 2, 3, 4, 5}, func(x int) bool { + return x == 3 +}) +// true +``` + +### Every + +Returns true if all elements of a subset are contained into a collection or if the subset is empty. + +```go +ok := lo.Every([]int{0, 1, 2, 3, 4, 5}, []int{0, 2}) +// true + +ok := lo.Every([]int{0, 1, 2, 3, 4, 5}, []int{0, 6}) +// false +``` + +### EveryBy + +Returns true if the predicate returns true for all elements in the collection or if the collection is empty. + +```go +b := EveryBy([]int{1, 2, 3, 4}, func(x int) bool { + return x < 5 +}) +// true +``` + +### Some + +Returns true if at least 1 element of a subset is contained into a collection. +If the subset is empty Some returns false. + +```go +ok := lo.Some([]int{0, 1, 2, 3, 4, 5}, []int{0, 6}) +// true + +ok := lo.Some([]int{0, 1, 2, 3, 4, 5}, []int{-1, 6}) +// false +``` + +### SomeBy + +Returns true if the predicate returns true for any of the elements in the collection. +If the collection is empty SomeBy returns false. + +```go +b := SomeBy([]int{1, 2, 3, 4}, func(x int) bool { + return x < 3 +}) +// true +``` + +### None + +Returns true if no element of a subset are contained into a collection or if the subset is empty. + +```go +b := None([]int{0, 1, 2, 3, 4, 5}, []int{0, 2}) +// false +b := None([]int{0, 1, 2, 3, 4, 5}, []int{-1, 6}) +// true +``` + +### NoneBy + +Returns true if the predicate returns true for none of the elements in the collection or if the collection is empty. + +```go +b := NoneBy([]int{1, 2, 3, 4}, func(x int) bool { + return x < 0 +}) +// true +``` + +### Intersect + +Returns the intersection between two collections. + +```go +result1 := lo.Intersect([]int{0, 1, 2, 3, 4, 5}, []int{0, 2}) +// []int{0, 2} + +result2 := lo.Intersect([]int{0, 1, 2, 3, 4, 5}, []int{0, 6}) +// []int{0} + +result3 := lo.Intersect([]int{0, 1, 2, 3, 4, 5}, []int{-1, 6}) +// []int{} +``` + +### Difference + +Returns the difference between two collections. + +- The first value is the collection of element absent of list2. +- The second value is the collection of element absent of list1. + +```go +left, right := lo.Difference([]int{0, 1, 2, 3, 4, 5}, []int{0, 2, 6}) +// []int{1, 3, 4, 5}, []int{6} + +left, right := lo.Difference([]int{0, 1, 2, 3, 4, 5}, []int{0, 1, 2, 3, 4, 5}) +// []int{}, []int{} +``` + +### Union + +Returns all distinct elements from given collections. Result will not change the order of elements relatively. + +```go +union := lo.Union([]int{0, 1, 2, 3, 4, 5}, []int{0, 2}, []int{0, 10}) +// []int{0, 1, 2, 3, 4, 5, 10} +``` + +### Without + +Returns slice excluding all given values. + +```go +subset := lo.Without([]int{0, 2, 10}, 2) +// []int{0, 10} + +subset := lo.Without([]int{0, 2, 10}, 0, 1, 2, 3, 4, 5) +// []int{10} +``` + +### WithoutBy + +Filters a slice by excluding elements whose extracted keys match any in the exclude list. + +It returns a new slice containing only the elements whose keys are not in the exclude list. + + +```go +type struct User { + ID int + Name string +} + +// original users +users := []User{ + {ID: 1, Name: "Alice"}, + {ID: 2, Name: "Bob"}, + {ID: 3, Name: "Charlie"}, +} + +// extract function to get the user ID +getID := func(user User) int { + return user.ID +} + +// exclude users with IDs 2 and 3 +excludedIDs := []int{2, 3} + +// filtering users +filteredUsers := lo.WithoutBy(users, getID, excludedIDs...) +// []User[{ID: 1, Name: "Alice"}] +``` + +### WithoutEmpty + +Returns slice excluding zero values. + +```go +subset := lo.WithoutEmpty([]int{0, 2, 10}) +// []int{2, 10} +``` + +### WithoutNth + +Returns slice excluding nth value. + +```go +subset := lo.WithoutNth([]int{-2, -1, 0, 1, 2}, 3, -42, 1) +// []int{-2, 0, 2} +``` + +### ElementsMatch + +Returns true if lists contain the same set of elements (including empty set). + +If there are duplicate elements, the number of appearances of each of them in both lists should match. + +The order of elements is not checked. + +```go +b := lo.ElementsMatch([]int{1, 1, 2}, []int{2, 1, 1}) +// true +``` + +### ElementsMatchBy + +Returns true if lists contain the same set of elements' keys (including empty set). + +If there are duplicate keys, the number of appearances of each of them in both lists should match. + +The order of elements is not checked. + +```go +b := lo.ElementsMatchBy( + []someType{a, b}, + []someType{b, a}, + func(item someType) string { return item.ID() }, +) +// true +``` + +### IndexOf + +Returns the index at which the first occurrence of a value is found in an array or return -1 if the value cannot be found. + +```go +found := lo.IndexOf([]int{0, 1, 2, 1, 2, 3}, 2) +// 2 + +notFound := lo.IndexOf([]int{0, 1, 2, 1, 2, 3}, 6) +// -1 +``` + +### LastIndexOf + +Returns the index at which the last occurrence of a value is found in an array or return -1 if the value cannot be found. + +```go +found := lo.LastIndexOf([]int{0, 1, 2, 1, 2, 3}, 2) +// 4 + +notFound := lo.LastIndexOf([]int{0, 1, 2, 1, 2, 3}, 6) +// -1 +``` + +### Find + +Search an element in a slice based on a predicate. It returns element and true if element was found. + +```go +str, ok := lo.Find([]string{"a", "b", "c", "d"}, func(i string) bool { + return i == "b" +}) +// "b", true + +str, ok := lo.Find([]string{"foobar"}, func(i string) bool { + return i == "b" +}) +// "", false +``` + +### FindIndexOf + +FindIndexOf searches an element in a slice based on a predicate and returns the index and true. It returns -1 and false if the element is not found. + +```go +str, index, ok := lo.FindIndexOf([]string{"a", "b", "a", "b"}, func(i string) bool { + return i == "b" +}) +// "b", 1, true + +str, index, ok := lo.FindIndexOf([]string{"foobar"}, func(i string) bool { + return i == "b" +}) +// "", -1, false +``` + +### FindLastIndexOf + +FindLastIndexOf searches an element in a slice based on a predicate and returns the index and true. It returns -1 and false if the element is not found. + +```go +str, index, ok := lo.FindLastIndexOf([]string{"a", "b", "a", "b"}, func(i string) bool { + return i == "b" +}) +// "b", 4, true + +str, index, ok := lo.FindLastIndexOf([]string{"foobar"}, func(i string) bool { + return i == "b" +}) +// "", -1, false +``` + +### FindOrElse + +Search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. + +```go +str := lo.FindOrElse([]string{"a", "b", "c", "d"}, "x", func(i string) bool { + return i == "b" +}) +// "b" + +str := lo.FindOrElse([]string{"foobar"}, "x", func(i string) bool { + return i == "b" +}) +// "x" +``` + +### FindKey + +Returns the key of the first value matching. + +```go +result1, ok1 := lo.FindKey(map[string]int{"foo": 1, "bar": 2, "baz": 3}, 2) +// "bar", true + +result2, ok2 := lo.FindKey(map[string]int{"foo": 1, "bar": 2, "baz": 3}, 42) +// "", false + +type test struct { + foobar string +} +result3, ok3 := lo.FindKey(map[string]test{"foo": test{"foo"}, "bar": test{"bar"}, "baz": test{"baz"}}, test{"foo"}) +// "foo", true +``` + +### FindKeyBy + +Returns the key of the first element predicate returns truthy for. + +```go +result1, ok1 := lo.FindKeyBy(map[string]int{"foo": 1, "bar": 2, "baz": 3}, func(k string, v int) bool { + return k == "foo" +}) +// "foo", true + +result2, ok2 := lo.FindKeyBy(map[string]int{"foo": 1, "bar": 2, "baz": 3}, func(k string, v int) bool { + return false +}) +// "", false +``` + +### FindUniques + +Returns a slice with all the unique elements of the collection. The order of result values is determined by the order they occur in the array. + +```go +uniqueValues := lo.FindUniques([]int{1, 2, 2, 1, 2, 3}) +// []int{3} +``` + +### FindUniquesBy + +Returns a slice with all the unique elements of the collection. The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is invoked for each element in array to generate the criterion by which uniqueness is computed. + +```go +uniqueValues := lo.FindUniquesBy([]int{3, 4, 5, 6, 7}, func(i int) int { + return i%3 +}) +// []int{5} +``` + +### FindDuplicates + +Returns a slice with the first occurrence of each duplicated elements of the collection. The order of result values is determined by the order they occur in the array. + +```go +duplicatedValues := lo.FindDuplicates([]int{1, 2, 2, 1, 2, 3}) +// []int{1, 2} +``` + +### FindDuplicatesBy + +Returns a slice with the first occurrence of each duplicated elements of the collection. The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is invoked for each element in array to generate the criterion by which uniqueness is computed. + +```go +duplicatedValues := lo.FindDuplicatesBy([]int{3, 4, 5, 6, 7}, func(i int) int { + return i%3 +}) +// []int{3, 4} +``` + +### Min + +Search the minimum value of a collection. + +Returns zero value when the collection is empty. + +```go +min := lo.Min([]int{1, 2, 3}) +// 1 + +min := lo.Min([]int{}) +// 0 + +min := lo.Min([]time.Duration{time.Second, time.Hour}) +// 1s +``` + +### MinIndex + +Search the minimum value of a collection and the index of the minimum value. + +Returns (zero value, -1) when the collection is empty. + +```go +min, index := lo.MinIndex([]int{1, 2, 3}) +// 1, 0 + +min, index := lo.MinIndex([]int{}) +// 0, -1 + +min, index := lo.MinIndex([]time.Duration{time.Second, time.Hour}) +// 1s, 0 +``` + +### MinBy + +Search the minimum value of a collection using the given comparison function. + +If several values of the collection are equal to the smallest value, returns the first such value. + +Returns zero value when the collection is empty. + +```go +min := lo.MinBy([]string{"s1", "string2", "s3"}, func(item string, min string) bool { + return len(item) < len(min) +}) +// "s1" + +min := lo.MinBy([]string{}, func(item string, min string) bool { + return len(item) < len(min) +}) +// "" +``` + +### MinIndexBy + +Search the minimum value of a collection using the given comparison function and the index of the minimum value. + +If several values of the collection are equal to the smallest value, returns the first such value. + +Returns (zero value, -1) when the collection is empty. + +```go +min, index := lo.MinIndexBy([]string{"s1", "string2", "s3"}, func(item string, min string) bool { + return len(item) < len(min) +}) +// "s1", 0 + +min, index := lo.MinIndexBy([]string{}, func(item string, min string) bool { + return len(item) < len(min) +}) +// "", -1 +``` + +### Earliest + +Search the minimum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +earliest := lo.Earliest(time.Now(), time.Time{}) +// 0001-01-01 00:00:00 +0000 UTC +``` + +### EarliestBy + +Search the minimum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +earliest := lo.EarliestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + +### Max + +Search the maximum value of a collection. + +Returns zero value when the collection is empty. + +```go +max := lo.Max([]int{1, 2, 3}) +// 3 + +max := lo.Max([]int{}) +// 0 + +max := lo.Max([]time.Duration{time.Second, time.Hour}) +// 1h +``` + +### MaxIndex + +Search the maximum value of a collection and the index of the maximum value. + +Returns (zero value, -1) when the collection is empty. + +```go +max, index := lo.MaxIndex([]int{1, 2, 3}) +// 3, 2 + +max, index := lo.MaxIndex([]int{}) +// 0, -1 + +max, index := lo.MaxIndex([]time.Duration{time.Second, time.Hour}) +// 1h, 1 +``` + +### MaxBy + +Search the maximum value of a collection using the given comparison function. + +If several values of the collection are equal to the greatest value, returns the first such value. + +Returns zero value when the collection is empty. + +```go +max := lo.MaxBy([]string{"string1", "s2", "string3"}, func(item string, max string) bool { + return len(item) > len(max) +}) +// "string1" + +max := lo.MaxBy([]string{}, func(item string, max string) bool { + return len(item) > len(max) +}) +// "" +``` + +### MaxIndexBy + +Search the maximum value of a collection using the given comparison function and the index of the maximum value. + +If several values of the collection are equal to the greatest value, returns the first such value. + +Returns (zero value, -1) when the collection is empty. + +```go +max, index := lo.MaxIndexBy([]string{"string1", "s2", "string3"}, func(item string, max string) bool { + return len(item) > len(max) +}) +// "string1", 0 + +max, index := lo.MaxIndexBy([]string{}, func(item string, max string) bool { + return len(item) > len(max) +}) +// "", -1 +``` + +### Latest + +Search the maximum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +latest := lo.Latest(time.Now(), time.Time{}) +// 2023-04-01 01:02:03 +0000 UTC +``` + +### LatestBy + +Search the maximum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +latest := lo.LatestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + +### First + +Returns the first element of a collection and check for availability of the first element. + +```go +first, ok := lo.First([]int{1, 2, 3}) +// 1, true + +first, ok := lo.First([]int{}) +// 0, false +``` + +### FirstOrEmpty + +Returns the first element of a collection or zero value if empty. + +```go +first := lo.FirstOrEmpty([]int{1, 2, 3}) +// 1 + +first := lo.FirstOrEmpty([]int{}) +// 0 +``` + +### FirstOr + +Returns the first element of a collection or the fallback value if empty. + +```go +first := lo.FirstOr([]int{1, 2, 3}, 245) +// 1 + +first := lo.FirstOr([]int{}, 31) +// 31 +``` + +### Last + +Returns the last element of a collection or error if empty. + +```go +last, ok := lo.Last([]int{1, 2, 3}) +// 3 +// true + +last, ok := lo.Last([]int{}) +// 0 +// false +``` + +### LastOrEmpty + +Returns the last element of a collection or zero value if empty. + +```go +last := lo.LastOrEmpty([]int{1, 2, 3}) +// 3 + +last := lo.LastOrEmpty([]int{}) +// 0 +``` + +### LastOr + +Returns the last element of a collection or the fallback value if empty. + +```go +last := lo.LastOr([]int{1, 2, 3}, 245) +// 3 + +last := lo.LastOr([]int{}, 31) +// 31 +``` + +### Nth + +Returns the element at index `nth` of collection. If `nth` is negative, the nth element from the end is returned. An error is returned when nth is out of slice bounds. + +```go +nth, err := lo.Nth([]int{0, 1, 2, 3}, 2) +// 2 + +nth, err := lo.Nth([]int{0, 1, 2, 3}, -2) +// 2 +``` + +### NthOr + +Returns the element at index `nth` of the collection. If `nth` is negative, it returns the `nth` element from the end. If `nth` is out of slice bounds, it returns the provided fallback value +```go +nth := lo.NthOr([]int{10, 20, 30, 40, 50}, 2, -1) +// 30 + +nth := lo.NthOr([]int{10, 20, 30, 40, 50}, -1, -1) +// 50 + +nth := lo.NthOr([]int{10, 20, 30, 40, 50}, 5, -1) +// -1 (fallback value) +``` + +### NthOrEmpty + +Returns the element at index `nth` of the collection. If `nth` is negative, it returns the `nth` element from the end. If `nth` is out of slice bounds, it returns the zero value for the element type (e.g., 0 for integers, "" for strings, etc). +``` go +nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, 2) +// 30 + +nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, -1) +// 50 + +nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, 5) +// 0 (zero value for int) + +nth := lo.NthOrEmpty([]string{"apple", "banana", "cherry"}, 2) +// "cherry" + +nth := lo.NthOrEmpty([]string{"apple", "banana", "cherry"}, 5) +// "" (zero value for string) +``` + +### Sample + +Returns a random item from collection. + +```go +lo.Sample([]string{"a", "b", "c"}) +// a random string from []string{"a", "b", "c"} + +lo.Sample([]string{}) +// "" +``` + + + +### SampleBy + +Returns a random item from collection, using a given random integer generator. + +```go +import "math/rand" + +r := rand.New(rand.NewSource(42)) +lo.SampleBy([]string{"a", "b", "c"}, r.Intn) +// a random string from []string{"a", "b", "c"}, using a seeded random generator + +lo.SampleBy([]string{}, r.Intn) +// "" +``` + +### Samples + +Returns N random unique items from collection. + +```go +lo.Samples([]string{"a", "b", "c"}, 3) +// []string{"a", "b", "c"} in random order +``` + +### SamplesBy + +Returns N random unique items from collection, using a given random integer generator. + +```go +r := rand.New(rand.NewSource(42)) +lo.SamplesBy([]string{"a", "b", "c"}, 3, r.Intn) +// []string{"a", "b", "c"} in random order, using a seeded random generator +``` + +### Ternary + +A 1 line if/else statement. + + +```go +result := lo.Ternary(true, "a", "b") +// "a" + +result := lo.Ternary(false, "a", "b") +// "b" +``` + +Take care to avoid dereferencing potentially nil pointers in your A/B expressions, because they are both evaluated. See TernaryF to avoid this problem. + +[[play](https://go.dev/play/p/t-D7WBL44h2)] + +### TernaryF + +A 1 line if/else statement whose options are functions. + +```go +result := lo.TernaryF(true, func() string { return "a" }, func() string { return "b" }) +// "a" + +result := lo.TernaryF(false, func() string { return "a" }, func() string { return "b" }) +// "b" +``` + +Useful to avoid nil-pointer dereferencing in initializations, or avoid running unnecessary code + +```go +var s *string + +someStr := TernaryF(s == nil, func() string { return uuid.New().String() }, func() string { return *s }) +// ef782193-c30c-4e2e-a7ae-f8ab5e125e02 +``` + +[[play](https://go.dev/play/p/AO4VW20JoqM)] + +### If / ElseIf / Else + +```go +result := lo.If(true, 1). + ElseIf(false, 2). + Else(3) +// 1 + +result := lo.If(false, 1). + ElseIf(true, 2). + Else(3) +// 2 + +result := lo.If(false, 1). + ElseIf(false, 2). + Else(3) +// 3 +``` + +Using callbacks: + +```go +result := lo.IfF(true, func () int { + return 1 + }). + ElseIfF(false, func () int { + return 2 + }). + ElseF(func () int { + return 3 + }) +// 1 +``` + +Mixed: + +```go +result := lo.IfF(true, func () int { + return 1 + }). + Else(42) +// 1 +``` + +[[play](https://go.dev/play/p/WSw3ApMxhyW)] + +### Switch / Case / Default + +```go +result := lo.Switch(1). + Case(1, "1"). + Case(2, "2"). + Default("3") +// "1" + +result := lo.Switch(2). + Case(1, "1"). + Case(2, "2"). + Default("3") +// "2" + +result := lo.Switch(42). + Case(1, "1"). + Case(2, "2"). + Default("3") +// "3" +``` + +Using callbacks: + +```go +result := lo.Switch(1). + CaseF(1, func() string { + return "1" + }). + CaseF(2, func() string { + return "2" + }). + DefaultF(func() string { + return "3" + }) +// "1" +``` + +Mixed: + +```go +result := lo.Switch(1). + CaseF(1, func() string { + return "1" + }). + Default("42") +// "1" +``` + +[[play](https://go.dev/play/p/TGbKUMAeRUd)] + +### IsNil + +Checks if a value is nil or if it's a reference type with a nil underlying value. + +```go +var x int +lo.IsNil(x) +// false + +var k struct{} +lo.IsNil(k) +// false + +var i *int +lo.IsNil(i) +// true + +var ifaceWithNilValue any = (*string)(nil) +lo.IsNil(ifaceWithNilValue) +// true +ifaceWithNilValue == nil +// false +``` + +### IsNotNil + +Checks if a value is not nil or if it's not a reference type with a nil underlying value. + +```go +var x int +lo.IsNotNil(x) +// true + +var k struct{} +lo.IsNotNil(k) +// true + +var i *int +lo.IsNotNil(i) +// false + +var ifaceWithNilValue any = (*string)(nil) +lo.IsNotNil(ifaceWithNilValue) +// false +ifaceWithNilValue == nil +// true +``` + +### ToPtr + +Returns a pointer copy of the value. + +```go +ptr := lo.ToPtr("hello world") +// *string{"hello world"} +``` + +### Nil + +Returns a nil pointer of type. + +```go +ptr := lo.Nil[float64]() +// nil +``` + +### EmptyableToPtr + +Returns a pointer copy of value if it's nonzero. +Otherwise, returns nil pointer. + +```go +ptr := lo.EmptyableToPtr(nil) +// nil + +ptr := lo.EmptyableToPtr("") +// nil + +ptr := lo.EmptyableToPtr([]int{}) +// *[]int{} + +ptr := lo.EmptyableToPtr("hello world") +// *string{"hello world"} +``` + +### FromPtr + +Returns the pointer value or empty. + +```go +str := "hello world" +value := lo.FromPtr(&str) +// "hello world" + +value := lo.FromPtr(nil) +// "" +``` + +### FromPtrOr + +Returns the pointer value or the fallback value. + +```go +str := "hello world" +value := lo.FromPtrOr(&str, "empty") +// "hello world" + +value := lo.FromPtrOr(nil, "empty") +// "empty" +``` + +### ToSlicePtr + +Returns a slice of pointer copy of value. + +```go +ptr := lo.ToSlicePtr([]string{"hello", "world"}) +// []*string{"hello", "world"} +``` + +### FromSlicePtr + +Returns a slice with the pointer values. +Returns a zero value in case of a nil pointer element. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}) +// []string{"hello", "world", ""} + +ptr := lo.Compact( + lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}), +) +// []string{"hello", "world"} +``` + +### FromSlicePtrOr + +Returns a slice with the pointer values or the fallback value. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtrOr([]*string{&str1, nil, &str2}, "fallback value") +// []string{"hello", "fallback value", "world"} +``` + +[[play](https://go.dev/play/p/CuXGVzo9G65)] + +### ToAnySlice + +Returns a slice with all elements mapped to `any` type. + +```go +elements := lo.ToAnySlice([]int{1, 5, 1}) +// []any{1, 5, 1} +``` + +### FromAnySlice + +Returns an `any` slice with all elements mapped to a type. Returns false in case of type conversion failure. + +```go +elements, ok := lo.FromAnySlice([]any{"foobar", 42}) +// []string{}, false + +elements, ok := lo.FromAnySlice([]any{"foobar", "42"}) +// []string{"foobar", "42"}, true +``` + +### Empty + +Returns the [zero value](https://go.dev/ref/spec#The_zero_value). + +```go +lo.Empty[int]() +// 0 +lo.Empty[string]() +// "" +lo.Empty[bool]() +// false +``` + +### IsEmpty + +Returns true if argument is a zero value. + +```go +lo.IsEmpty(0) +// true +lo.IsEmpty(42) +// false + +lo.IsEmpty("") +// true +lo.IsEmpty("foobar") +// false + +type test struct { + foobar string +} + +lo.IsEmpty(test{foobar: ""}) +// true +lo.IsEmpty(test{foobar: "foobar"}) +// false +``` + +### IsNotEmpty + +Returns true if argument is a zero value. + +```go +lo.IsNotEmpty(0) +// false +lo.IsNotEmpty(42) +// true + +lo.IsNotEmpty("") +// false +lo.IsNotEmpty("foobar") +// true + +type test struct { + foobar string +} + +lo.IsNotEmpty(test{foobar: ""}) +// false +lo.IsNotEmpty(test{foobar: "foobar"}) +// true +``` + +### Coalesce + +Returns the first non-empty arguments. Arguments must be comparable. + +```go +result, ok := lo.Coalesce(0, 1, 2, 3) +// 1 true + +result, ok := lo.Coalesce("") +// "" false + +var nilStr *string +str := "foobar" +result, ok := lo.Coalesce(nil, nilStr, &str) +// &"foobar" true +``` + +### CoalesceOrEmpty + +Returns the first non-empty arguments. Arguments must be comparable. + +```go +result := lo.CoalesceOrEmpty(0, 1, 2, 3) +// 1 + +result := lo.CoalesceOrEmpty("") +// "" + +var nilStr *string +str := "foobar" +result := lo.CoalesceOrEmpty(nil, nilStr, &str) +// &"foobar" +``` + +### CoalesceSlice + +Returns the first non-zero slice. + +```go +result, ok := lo.CoalesceSlice([]int{1, 2, 3}, []int{4, 5, 6}) +// [1, 2, 3] +// true + +result, ok := lo.CoalesceSlice(nil, []int{}) +// [] +// true + +result, ok := lo.CoalesceSlice([]int(nil)) +// [] +// false +``` + +### CoalesceSliceOrEmpty + +Returns the first non-zero slice. + +```go +result := lo.CoalesceSliceOrEmpty([]int{1, 2, 3}, []int{4, 5, 6}) +// [1, 2, 3] + +result := lo.CoalesceSliceOrEmpty(nil, []int{}) +// [] +``` + +### CoalesceMap + +Returns the first non-zero map. + +```go +result, ok := lo.CoalesceMap(map[string]int{"1": 1, "2": 2, "3": 3}, map[string]int{"4": 4, "5": 5, "6": 6}) +// {"1": 1, "2": 2, "3": 3} +// true + +result, ok := lo.CoalesceMap(nil, map[string]int{}) +// {} +// true + +result, ok := lo.CoalesceMap(map[string]int(nil)) +// {} +// false +``` + +### CoalesceMapOrEmpty + +Returns the first non-zero map. + +```go +result := lo.CoalesceMapOrEmpty(map[string]int{"1": 1, "2": 2, "3": 3}, map[string]int{"4": 4, "5": 5, "6": 6}) +// {"1": 1, "2": 2, "3": 3} + +result := lo.CoalesceMapOrEmpty(nil, map[string]int{}) +// {} +``` + +### Partial + +Returns new function that, when called, has its first argument set to the provided value. + +```go +add := func(x, y int) int { return x + y } +f := lo.Partial(add, 5) + +f(10) +// 15 + +f(42) +// 47 +``` + +### Partial2 -> Partial5 + +Returns new function that, when called, has its first argument set to the provided value. + +```go +add := func(x, y, z int) int { return x + y + z } +f := lo.Partial2(add, 42) + +f(10, 5) +// 57 + +f(42, -4) +// 80 +``` + +### Attempt + +Invokes a function N times until it returns valid output. Returns either the caught error or nil. + +When the first argument is less than `1`, the function runs until a successful response is returned. + +```go +iter, err := lo.Attempt(42, func(i int) error { + if i == 5 { + return nil + } + + return fmt.Errorf("failed") +}) +// 6 +// nil + +iter, err := lo.Attempt(2, func(i int) error { + if i == 5 { + return nil + } + + return fmt.Errorf("failed") +}) +// 2 +// error "failed" + +iter, err := lo.Attempt(0, func(i int) error { + if i < 42 { + return fmt.Errorf("failed") + } + + return nil +}) +// 43 +// nil +``` + +For more advanced retry strategies (delay, exponential backoff...), please take a look on [cenkalti/backoff](https://github.com/cenkalti/backoff). + +[[play](https://go.dev/play/p/3ggJZ2ZKcMj)] + +### AttemptWithDelay + +Invokes a function N times until it returns valid output, with a pause between each call. Returns either the caught error or nil. + +When the first argument is less than `1`, the function runs until a successful response is returned. + +```go +iter, duration, err := lo.AttemptWithDelay(5, 2*time.Second, func(i int, duration time.Duration) error { + if i == 2 { + return nil + } + + return fmt.Errorf("failed") +}) +// 3 +// ~ 4 seconds +// nil +``` + +For more advanced retry strategies (delay, exponential backoff...), please take a look on [cenkalti/backoff](https://github.com/cenkalti/backoff). + +[[play](https://go.dev/play/p/tVs6CygC7m1)] + +### AttemptWhile + +Invokes a function N times until it returns valid output. Returns either the caught error or nil, along with a bool value to determine whether the function should be invoked again. It will terminate the invoke immediately if the second return value is false. + +When the first argument is less than `1`, the function runs until a successful response is returned. + +```go +count1, err1 := lo.AttemptWhile(5, func(i int) (error, bool) { + err := doMockedHTTPRequest(i) + if err != nil { + if errors.Is(err, ErrBadRequest) { // lets assume ErrBadRequest is a critical error that needs to terminate the invoke + return err, false // flag the second return value as false to terminate the invoke + } + + return err, true + } + + return nil, false +}) +``` + +For more advanced retry strategies (delay, exponential backoff...), please take a look on [cenkalti/backoff](https://github.com/cenkalti/backoff). + +[[play](https://go.dev/play/p/M2wVq24PaZM)] + +### AttemptWhileWithDelay + +Invokes a function N times until it returns valid output, with a pause between each call. Returns either the caught error or nil, along with a bool value to determine whether the function should be invoked again. It will terminate the invoke immediately if the second return value is false. + +When the first argument is less than `1`, the function runs until a successful response is returned. + +```go +count1, time1, err1 := lo.AttemptWhileWithDelay(5, time.Millisecond, func(i int, d time.Duration) (error, bool) { + err := doMockedHTTPRequest(i) + if err != nil { + if errors.Is(err, ErrBadRequest) { // lets assume ErrBadRequest is a critical error that needs to terminate the invoke + return err, false // flag the second return value as false to terminate the invoke + } + + return err, true + } + + return nil, false +}) +``` + +For more advanced retry strategies (delay, exponential backoff...), please take a look on [cenkalti/backoff](https://github.com/cenkalti/backoff). + +[[play](https://go.dev/play/p/cfcmhvLO-nv)] + +### Debounce + +`NewDebounce` creates a debounced instance that delays invoking functions given until after wait milliseconds have elapsed, until `cancel` is called. + +```go +f := func() { + println("Called once after 100ms when debounce stopped invoking!") +} + +debounce, cancel := lo.NewDebounce(100 * time.Millisecond, f) +for j := 0; j < 10; j++ { + debounce() +} + +time.Sleep(1 * time.Second) +cancel() +``` + +[[play](https://go.dev/play/p/mz32VMK2nqe)] + +### DebounceBy + +`NewDebounceBy` creates a debounced instance for each distinct key, that delays invoking functions given until after wait milliseconds have elapsed, until `cancel` is called. + +```go +f := func(key string, count int) { + println(key + ": Called once after 100ms when debounce stopped invoking!") +} + +debounce, cancel := lo.NewDebounceBy(100 * time.Millisecond, f) +for j := 0; j < 10; j++ { + debounce("first key") + debounce("second key") +} + +time.Sleep(1 * time.Second) +cancel("first key") +cancel("second key") +``` + +[[play](https://go.dev/play/p/d3Vpt6pxhY8)] + +### Throttle + +Creates a throttled instance that invokes given functions only once in every interval. + +This returns 2 functions, First one is throttled function and Second one is a function to reset interval. + +```go +f := func() { + println("Called once in every 100ms") +} + +throttle, reset := lo.NewThrottle(100 * time.Millisecond, f) + +for j := 0; j < 10; j++ { + throttle() + time.Sleep(30 * time.Millisecond) +} + +reset() +throttle() +``` + +`NewThrottleWithCount` is NewThrottle with count limit, throttled function will be invoked count times in every interval. + +```go +f := func() { + println("Called three times in every 100ms") +} + +throttle, reset := lo.NewThrottleWithCount(100 * time.Millisecond, f) + +for j := 0; j < 10; j++ { + throttle() + time.Sleep(30 * time.Millisecond) +} + +reset() +throttle() +``` + +`NewThrottleBy` and `NewThrottleByWithCount` are NewThrottle with sharding key, throttled function will be invoked count times in every interval. + +```go +f := func(key string) { + println(key, "Called three times in every 100ms") +} + +throttle, reset := lo.NewThrottleByWithCount(100 * time.Millisecond, f) + +for j := 0; j < 10; j++ { + throttle("foo") + time.Sleep(30 * time.Millisecond) +} + +reset() +throttle() +``` + +### Synchronize + +Wraps the underlying callback in a mutex. It receives an optional mutex. + +```go +s := lo.Synchronize() + +for i := 0; i < 10; i++ { + go s.Do(func () { + println("will be called sequentially") + }) +} +``` + +It is equivalent to: + +```go +mu := sync.Mutex{} + +func foobar() { + mu.Lock() + defer mu.Unlock() + + // ... +} +``` + +### Async + +Executes a function in a goroutine and returns the result in a channel. + +```go +ch := lo.Async(func() error { time.Sleep(10 * time.Second); return nil }) +// chan error (nil) +``` + +### Async{0->6} + +Executes a function in a goroutine and returns the result in a channel. +For function with multiple return values, the results will be returned as a tuple inside the channel. +For function without return, struct{} will be returned in the channel. + +```go +ch := lo.Async0(func() { time.Sleep(10 * time.Second) }) +// chan struct{} + +ch := lo.Async1(func() int { + time.Sleep(10 * time.Second); + return 42 +}) +// chan int (42) + +ch := lo.Async2(func() (int, string) { + time.Sleep(10 * time.Second); + return 42, "Hello" +}) +// chan lo.Tuple2[int, string] ({42, "Hello"}) +``` + +### Transaction + +Implements a Saga pattern. + +```go +transaction := NewTransaction(). + Then( + func(state int) (int, error) { + fmt.Println("step 1") + return state + 10, nil + }, + func(state int) int { + fmt.Println("rollback 1") + return state - 10 + }, + ). + Then( + func(state int) (int, error) { + fmt.Println("step 2") + return state + 15, nil + }, + func(state int) int { + fmt.Println("rollback 2") + return state - 15 + }, + ). + Then( + func(state int) (int, error) { + fmt.Println("step 3") + + if true { + return state, fmt.Errorf("error") + } + + return state + 42, nil + }, + func(state int) int { + fmt.Println("rollback 3") + return state - 42 + }, + ) + +_, _ = transaction.Process(-5) + +// Output: +// step 1 +// step 2 +// step 3 +// rollback 2 +// rollback 1 +``` + +### WaitFor + +Runs periodically until a condition is validated. + +```go +alwaysTrue := func(i int) bool { return true } +alwaysFalse := func(i int) bool { return false } +laterTrue := func(i int) bool { + return i > 5 +} + +iterations, duration, ok := lo.WaitFor(alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitFor(alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, time.Millisecond) +// 7 +// 7ms +// true + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false +``` + +### WaitForWithContext + +Runs periodically until a condition is validated or context is invalid. + +The condition receives also the context, so it can invalidate the process in the condition checker + +```go +ctx := context.Background() + +alwaysTrue := func(_ context.Context, i int) bool { return true } +alwaysFalse := func(_ context.Context, i int) bool { return false } +laterTrue := func(_ context.Context, i int) bool { + return i >= 5 +} + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, time.Millisecond) +// 5 +// 5ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false + +expiringCtx, cancel := context.WithTimeout(ctx, 5*time.Millisecond) +iterations, duration, ok := lo.WaitForWithContext(expiringCtx, alwaysFalse, 100*time.Millisecond, time.Millisecond) +// 5 +// 5.1ms +// false +``` + +### Validate + +Helper function that creates an error when a condition is not met. + +```go +slice := []string{"a"} +val := lo.Validate(len(slice) == 0, "Slice should be empty but contains %v", slice) +// error("Slice should be empty but contains [a]") + +slice := []string{} +val := lo.Validate(len(slice) == 0, "Slice should be empty but contains %v", slice) +// nil +``` + +[[play](https://go.dev/play/p/vPyh51XpCBt)] + +### Must + +Wraps a function call to panics if second argument is `error` or `false`, returns the value otherwise. + +```go +val := lo.Must(time.Parse("2006-01-02", "2022-01-15")) +// 2022-01-15 + +val := lo.Must(time.Parse("2006-01-02", "bad-value")) +// panics +``` + +[[play](https://go.dev/play/p/TMoWrRp3DyC)] + +### Must{0->6} + +Must\* has the same behavior as Must, but returns multiple values. + +```go +func example0() (error) +func example1() (int, error) +func example2() (int, string, error) +func example3() (int, string, time.Date, error) +func example4() (int, string, time.Date, bool, error) +func example5() (int, string, time.Date, bool, float64, error) +func example6() (int, string, time.Date, bool, float64, byte, error) + +lo.Must0(example0()) +val1 := lo.Must1(example1()) // alias to Must +val1, val2 := lo.Must2(example2()) +val1, val2, val3 := lo.Must3(example3()) +val1, val2, val3, val4 := lo.Must4(example4()) +val1, val2, val3, val4, val5 := lo.Must5(example5()) +val1, val2, val3, val4, val5, val6 := lo.Must6(example6()) +``` + +You can wrap functions like `func (...) (..., ok bool)`. + +```go +// math.Signbit(float64) bool +lo.Must0(math.Signbit(v)) + +// bytes.Cut([]byte,[]byte) ([]byte, []byte, bool) +before, after := lo.Must2(bytes.Cut(s, sep)) +``` + +You can give context to the panic message by adding some printf-like arguments. + +```go +val, ok := lo.Find(myString, func(i string) bool { + return i == requiredChar +}) +lo.Must0(ok, "'%s' must always contain '%s'", myString, requiredChar) + +list := []int{0, 1, 2} +item := 5 +lo.Must0(lo.Contains(list, item), "'%s' must always contain '%s'", list, item) +... +``` + +[[play](https://go.dev/play/p/TMoWrRp3DyC)] + +### Try + +Calls the function and returns false in case of error and panic. + +```go +ok := lo.Try(func() error { + panic("error") + return nil +}) +// false + +ok := lo.Try(func() error { + return nil +}) +// true + +ok := lo.Try(func() error { + return fmt.Errorf("error") +}) +// false +``` + +[[play](https://go.dev/play/p/mTyyWUvn9u4)] + +### Try{0->6} + +The same behavior as `Try`, but the callback returns 2 variables. + +```go +ok := lo.Try2(func() (string, error) { + panic("error") + return "", nil +}) +// false +``` + +[[play](https://go.dev/play/p/mTyyWUvn9u4)] + +### TryOr + +Calls the function and return a default value in case of error and on panic. + +```go +str, ok := lo.TryOr(func() (string, error) { + panic("error") + return "hello", nil +}, "world") +// world +// false + +str, ok := lo.TryOr(func() error { + return "hello", nil +}, "world") +// hello +// true + +str, ok := lo.TryOr(func() error { + return "hello", fmt.Errorf("error") +}, "world") +// world +// false +``` + +[[play](https://go.dev/play/p/B4F7Wg2Zh9X)] + +### TryOr{0->6} + +The same behavior as `TryOr`, but the callback returns `X` variables. + +```go +str, nbr, ok := lo.TryOr2(func() (string, int, error) { + panic("error") + return "hello", 42, nil +}, "world", 21) +// world +// 21 +// false +``` + +[[play](https://go.dev/play/p/B4F7Wg2Zh9X)] + +### TryWithErrorValue + +The same behavior as `Try`, but also returns the value passed to panic. + +```go +err, ok := lo.TryWithErrorValue(func() error { + panic("error") + return nil +}) +// "error", false +``` + +[[play](https://go.dev/play/p/Kc7afQIT2Fs)] + +### TryCatch + +The same behavior as `Try`, but calls the catch function in case of error. + +```go +caught := false + +ok := lo.TryCatch(func() error { + panic("error") + return nil +}, func() { + caught = true +}) +// false +// caught == true +``` + +[[play](https://go.dev/play/p/PnOON-EqBiU)] + +### TryCatchWithErrorValue + +The same behavior as `TryWithErrorValue`, but calls the catch function in case of error. + +```go +caught := false + +ok := lo.TryCatchWithErrorValue(func() error { + panic("error") + return nil +}, func(val any) { + caught = val == "error" +}) +// false +// caught == true +``` + +[[play](https://go.dev/play/p/8Pc9gwX_GZO)] + +### ErrorsAs + +A shortcut for: + +```go +err := doSomething() + +var rateLimitErr *RateLimitError +if ok := errors.As(err, &rateLimitErr); ok { + // retry later +} +``` + +1 line `lo` helper: + +```go +err := doSomething() + +if rateLimitErr, ok := lo.ErrorsAs[*RateLimitError](err); ok { + // retry later +} +``` + +[[play](https://go.dev/play/p/8wk5rH8UfrE)] + +### Assert + +Does nothing when the condition is `true`, otherwise it panics with an optional message. + +Think twice before using it, given that [Go intentionally omits assertions from its standard library](https://go.dev/doc/faq#assertions). + +```go +age := getUserAge() + +lo.Assert(age >= 15) +``` + +```go +age := getUserAge() + +lo.Assert(age >= 15, "user age must be >= 15") +``` + +[[play](https://go.dev/play/p/Xv8LLKBMNwI)] + +### Assertf + +Like `Assert`, but with `fmt.Printf`-like formatting. + +Think twice before using it, given that [Go intentionally omits assertions from its standard library](https://go.dev/doc/faq#assertions). + +```go +age := getUserAge() + +lo.Assertf(age >= 15, "user age must be >= 15, got %d", age) +``` + +[[play](https://go.dev/play/p/TVPEmVcyrdY)] + +## 🛩 Benchmark + +We executed a simple benchmark with a dead-simple `lo.Map` loop: + +See the full implementation [here](./map_benchmark_test.go). + +```go +_ = lo.Map[int64](arr, func(x int64, i int) string { + return strconv.FormatInt(x, 10) +}) +``` + +**Result:** + +Here is a comparison between `lo.Map`, `lop.Map`, `go-funk` library and a simple Go `for` loop. + +```shell +$ go test -benchmem -bench ./... +goos: linux +goarch: amd64 +pkg: github.com/samber/lo +cpu: Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz +cpu: Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz +BenchmarkMap/lo.Map-8 8 132728237 ns/op 39998945 B/op 1000002 allocs/op +BenchmarkMap/lop.Map-8 2 503947830 ns/op 119999956 B/op 3000007 allocs/op +BenchmarkMap/reflect-8 2 826400560 ns/op 170326512 B/op 4000042 allocs/op +BenchmarkMap/for-8 9 126252954 ns/op 39998674 B/op 1000001 allocs/op +PASS +ok github.com/samber/lo 6.657s +``` + +- `lo.Map` is way faster (x7) than `go-funk`, a reflection-based Map implementation. +- `lo.Map` has the same allocation profile as `for`. +- `lo.Map` is 4% slower than `for`. +- `lop.Map` is slower than `lo.Map` because it implies more memory allocation and locks. `lop.Map` will be useful for long-running callbacks, such as i/o bound processing. +- `for` beats other implementations for memory and CPU. + +## 🤝 Contributing + +- Ping me on Twitter [@samuelberthe](https://twitter.com/samuelberthe) (DMs, mentions, whatever :)) +- Fork the [project](https://github.com/samber/lo) +- Fix [open issues](https://github.com/samber/lo/issues) or request new features + +Don't hesitate ;) + +Helper naming: helpers must be self-explanatory and respect standards (other languages, libraries...). Feel free to suggest many names in your contributions. + +### With Docker + +```bash +docker-compose run --rm dev +``` + +### Without Docker + +```bash +# Install some dev dependencies +make tools + +# Run tests +make test +# or +make watch-test +``` + +## 👤 Contributors + +![Contributors](https://contrib.rocks/image?repo=samber/lo) + +## 💫 Show your support + +Give a ⭐️ if this project helped you! + +[![GitHub Sponsors](https://img.shields.io/github/sponsors/samber?style=for-the-badge)](https://github.com/sponsors/samber) + +## 📝 License + +Copyright © 2022 [Samuel Berthe](https://github.com/samber). + +This project is under [MIT](./LICENSE) license. diff --git a/vendor/github.com/samber/lo/channel.go b/vendor/github.com/samber/lo/channel.go new file mode 100644 index 0000000000..a1e2cddcfb --- /dev/null +++ b/vendor/github.com/samber/lo/channel.go @@ -0,0 +1,314 @@ +package lo + +import ( + "context" + "sync" + "time" + + "github.com/samber/lo/internal/rand" +) + +type DispatchingStrategy[T any] func(msg T, index uint64, channels []<-chan T) int + +// ChannelDispatcher distributes messages from input channels into N child channels. +// Close events are propagated to children. +// Underlying channels can have a fixed buffer capacity or be unbuffered when cap is 0. +func ChannelDispatcher[T any](stream <-chan T, count int, channelBufferCap int, strategy DispatchingStrategy[T]) []<-chan T { + children := createChannels[T](count, channelBufferCap) + + roChildren := channelsToReadOnly(children) + + go func() { + // propagate channel closing to children + defer closeChannels(children) + + var i uint64 = 0 + + for { + msg, ok := <-stream + if !ok { + return + } + + destination := strategy(msg, i, roChildren) % count + children[destination] <- msg + + i++ + } + }() + + return roChildren +} + +func createChannels[T any](count int, channelBufferCap int) []chan T { + children := make([]chan T, 0, count) + + for i := 0; i < count; i++ { + children = append(children, make(chan T, channelBufferCap)) + } + + return children +} + +func channelsToReadOnly[T any](children []chan T) []<-chan T { + roChildren := make([]<-chan T, 0, len(children)) + + for i := range children { + roChildren = append(roChildren, children[i]) + } + + return roChildren +} + +func closeChannels[T any](children []chan T) { + for i := 0; i < len(children); i++ { + close(children[i]) + } +} + +func channelIsNotFull[T any](ch <-chan T) bool { + return cap(ch) == 0 || len(ch) < cap(ch) +} + +// DispatchingStrategyRoundRobin distributes messages in a rotating sequential manner. +// If the channel capacity is exceeded, the next channel will be selected and so on. +func DispatchingStrategyRoundRobin[T any](msg T, index uint64, channels []<-chan T) int { + for { + i := int(index % uint64(len(channels))) + if channelIsNotFull(channels[i]) { + return i + } + + index++ + time.Sleep(10 * time.Microsecond) // prevent CPU from burning 🔥 + } +} + +// DispatchingStrategyRandom distributes messages in a random manner. +// If the channel capacity is exceeded, another random channel will be selected and so on. +func DispatchingStrategyRandom[T any](msg T, index uint64, channels []<-chan T) int { + for { + i := rand.IntN(len(channels)) + if channelIsNotFull(channels[i]) { + return i + } + + time.Sleep(10 * time.Microsecond) // prevent CPU from burning 🔥 + } +} + +// DispatchingStrategyWeightedRandom distributes messages in a weighted manner. +// If the channel capacity is exceeded, another random channel will be selected and so on. +func DispatchingStrategyWeightedRandom[T any](weights []int) DispatchingStrategy[T] { + seq := []int{} + + for i := 0; i < len(weights); i++ { + for j := 0; j < weights[i]; j++ { + seq = append(seq, i) + } + } + + return func(msg T, index uint64, channels []<-chan T) int { + for { + i := seq[rand.IntN(len(seq))] + if channelIsNotFull(channels[i]) { + return i + } + + time.Sleep(10 * time.Microsecond) // prevent CPU from burning 🔥 + } + } +} + +// DispatchingStrategyFirst distributes messages in the first non-full channel. +// If the capacity of the first channel is exceeded, the second channel will be selected and so on. +func DispatchingStrategyFirst[T any](msg T, index uint64, channels []<-chan T) int { + for { + for i := range channels { + if channelIsNotFull(channels[i]) { + return i + } + } + + time.Sleep(10 * time.Microsecond) // prevent CPU from burning 🔥 + } +} + +// DispatchingStrategyLeast distributes messages in the emptiest channel. +func DispatchingStrategyLeast[T any](msg T, index uint64, channels []<-chan T) int { + seq := Range(len(channels)) + + return MinBy(seq, func(item int, min int) bool { + return len(channels[item]) < len(channels[min]) + }) +} + +// DispatchingStrategyMost distributes messages in the fullest channel. +// If the channel capacity is exceeded, the next channel will be selected and so on. +func DispatchingStrategyMost[T any](msg T, index uint64, channels []<-chan T) int { + seq := Range(len(channels)) + + return MaxBy(seq, func(item int, max int) bool { + return len(channels[item]) > len(channels[max]) && channelIsNotFull(channels[item]) + }) +} + +// SliceToChannel returns a read-only channels of collection elements. +func SliceToChannel[T any](bufferSize int, collection []T) <-chan T { + ch := make(chan T, bufferSize) + + go func() { + for i := range collection { + ch <- collection[i] + } + + close(ch) + }() + + return ch +} + +// ChannelToSlice returns a slice built from channels items. Blocks until channel closes. +func ChannelToSlice[T any](ch <-chan T) []T { + collection := []T{} + + for item := range ch { + collection = append(collection, item) + } + + return collection +} + +// Generator implements the generator design pattern. +func Generator[T any](bufferSize int, generator func(yield func(T))) <-chan T { + ch := make(chan T, bufferSize) + + go func() { + // WARNING: infinite loop + generator(func(t T) { + ch <- t + }) + + close(ch) + }() + + return ch +} + +// Buffer creates a slice of n elements from a channel. Returns the slice and the slice length. +// @TODO: we should probably provide an helper that reuse the same buffer. +func Buffer[T any](ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) { + buffer := make([]T, 0, size) + index := 0 + now := time.Now() + + for ; index < size; index++ { + item, ok := <-ch + if !ok { + return buffer, index, time.Since(now), false + } + + buffer = append(buffer, item) + } + + return buffer, index, time.Since(now), true +} + +// Batch creates a slice of n elements from a channel. Returns the slice and the slice length. +// +// Deprecated: Use [Buffer] instead. +func Batch[T any](ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) { + return Buffer(ch, size) +} + +// BufferWithContext creates a slice of n elements from a channel, with context. Returns the slice and the slice length. +// @TODO: we should probably provide an helper that reuse the same buffer. +func BufferWithContext[T any](ctx context.Context, ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) { + buffer := make([]T, 0, size) + now := time.Now() + + for index := 0; index < size; index++ { + select { + case item, ok := <-ch: + if !ok { + return buffer, index, time.Since(now), false + } + + buffer = append(buffer, item) + + case <-ctx.Done(): + return buffer, index, time.Since(now), true + } + } + + return buffer, size, time.Since(now), true +} + +// BufferWithTimeout creates a slice of n elements from a channel, with timeout. Returns the slice and the slice length. +func BufferWithTimeout[T any](ch <-chan T, size int, timeout time.Duration) (collection []T, length int, readTime time.Duration, ok bool) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return BufferWithContext(ctx, ch, size) +} + +// BatchWithTimeout creates a slice of n elements from a channel, with timeout. Returns the slice and the slice length. +// +// Deprecated: Use [BufferWithTimeout] instead. +func BatchWithTimeout[T any](ch <-chan T, size int, timeout time.Duration) (collection []T, length int, readTime time.Duration, ok bool) { + return BufferWithTimeout(ch, size, timeout) +} + +// FanIn collects messages from multiple input channels into a single buffered channel. +// Output messages has no priority. When all upstream channels reach EOF, downstream channel closes. +func FanIn[T any](channelBufferCap int, upstreams ...<-chan T) <-chan T { + out := make(chan T, channelBufferCap) + var wg sync.WaitGroup + + // Start an output goroutine for each input channel in upstreams. + wg.Add(len(upstreams)) + for i := range upstreams { + go func(index int) { + for n := range upstreams[index] { + out <- n + } + wg.Done() + }(i) + } + + // Start a goroutine to close out once all the output goroutines are done. + go func() { + wg.Wait() + close(out) + }() + return out +} + +// ChannelMerge collects messages from multiple input channels into a single buffered channel. +// Output messages has no priority. When all upstream channels reach EOF, downstream channel closes. +// +// Deprecated: Use [FanIn] instead. +func ChannelMerge[T any](channelBufferCap int, upstreams ...<-chan T) <-chan T { + return FanIn(channelBufferCap, upstreams...) +} + +// FanOut broadcasts all the upstream messages to multiple downstream channels. +// When upstream channel reach EOF, downstream channels close. If any downstream +// channels is full, broadcasting is paused. +func FanOut[T any](count int, channelsBufferCap int, upstream <-chan T) []<-chan T { + downstreams := createChannels[T](count, channelsBufferCap) + + go func() { + for msg := range upstream { + for i := range downstreams { + downstreams[i] <- msg + } + } + + // Close out once all the output goroutines are done. + for i := range downstreams { + close(downstreams[i]) + } + }() + + return channelsToReadOnly(downstreams) +} diff --git a/vendor/github.com/samber/lo/concurrency.go b/vendor/github.com/samber/lo/concurrency.go new file mode 100644 index 0000000000..a2ebbce20a --- /dev/null +++ b/vendor/github.com/samber/lo/concurrency.go @@ -0,0 +1,136 @@ +package lo + +import ( + "context" + "sync" + "time" +) + +type synchronize struct { + locker sync.Locker +} + +func (s *synchronize) Do(cb func()) { + s.locker.Lock() + Try0(cb) + s.locker.Unlock() +} + +// Synchronize wraps the underlying callback in a mutex. It receives an optional mutex. +func Synchronize(opt ...sync.Locker) *synchronize { + if len(opt) > 1 { + panic("unexpected arguments") + } else if len(opt) == 0 { + opt = append(opt, &sync.Mutex{}) + } + + return &synchronize{ + locker: opt[0], + } +} + +// Async executes a function in a goroutine and returns the result in a channel. +func Async[A any](f func() A) <-chan A { + ch := make(chan A, 1) + go func() { + ch <- f() + }() + return ch +} + +// Async0 executes a function in a goroutine and returns a channel set once the function finishes. +func Async0(f func()) <-chan struct{} { + ch := make(chan struct{}, 1) + go func() { + f() + ch <- struct{}{} + }() + return ch +} + +// Async1 is an alias to Async. +func Async1[A any](f func() A) <-chan A { + return Async(f) +} + +// Async2 has the same behavior as Async, but returns the 2 results as a tuple inside the channel. +func Async2[A, B any](f func() (A, B)) <-chan Tuple2[A, B] { + ch := make(chan Tuple2[A, B], 1) + go func() { + ch <- T2(f()) + }() + return ch +} + +// Async3 has the same behavior as Async, but returns the 3 results as a tuple inside the channel. +func Async3[A, B, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { + ch := make(chan Tuple3[A, B, C], 1) + go func() { + ch <- T3(f()) + }() + return ch +} + +// Async4 has the same behavior as Async, but returns the 4 results as a tuple inside the channel. +func Async4[A, B, C, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] { + ch := make(chan Tuple4[A, B, C, D], 1) + go func() { + ch <- T4(f()) + }() + return ch +} + +// Async5 has the same behavior as Async, but returns the 5 results as a tuple inside the channel. +func Async5[A, B, C, D, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] { + ch := make(chan Tuple5[A, B, C, D, E], 1) + go func() { + ch <- T5(f()) + }() + return ch +} + +// Async6 has the same behavior as Async, but returns the 6 results as a tuple inside the channel. +func Async6[A, B, C, D, E, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] { + ch := make(chan Tuple6[A, B, C, D, E, F], 1) + go func() { + ch <- T6(f()) + }() + return ch +} + +// WaitFor runs periodically until a condition is validated. +func WaitFor(condition func(i int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + conditionWithContext := func(_ context.Context, currentIteration int) bool { + return condition(currentIteration) + } + return WaitForWithContext(context.Background(), conditionWithContext, timeout, heartbeatDelay) +} + +// WaitForWithContext runs periodically until a condition is validated or context is canceled. +func WaitForWithContext(ctx context.Context, condition func(ctx context.Context, currentIteration int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + start := time.Now() + + if ctx.Err() != nil { + return totalIterations, time.Since(start), false + } + + ctx, cleanCtx := context.WithTimeout(ctx, timeout) + ticker := time.NewTicker(heartbeatDelay) + + defer func() { + cleanCtx() + ticker.Stop() + }() + + for { + select { + case <-ctx.Done(): + return totalIterations, time.Since(start), false + case <-ticker.C: + totalIterations++ + if condition(ctx, totalIterations-1) { + return totalIterations, time.Since(start), true + } + } + } +} diff --git a/vendor/github.com/samber/lo/condition.go b/vendor/github.com/samber/lo/condition.go new file mode 100644 index 0000000000..eaeaa2b952 --- /dev/null +++ b/vendor/github.com/samber/lo/condition.go @@ -0,0 +1,151 @@ +package lo + +// Ternary is a 1 line if/else statement. +// Take care to avoid dereferencing potentially nil pointers in your A/B expressions, because they are both evaluated. See TernaryF to avoid this problem. +// Play: https://go.dev/play/p/t-D7WBL44h2 +func Ternary[T any](condition bool, ifOutput T, elseOutput T) T { + if condition { + return ifOutput + } + + return elseOutput +} + +// TernaryF is a 1 line if/else statement whose options are functions +// Play: https://go.dev/play/p/AO4VW20JoqM +func TernaryF[T any](condition bool, ifFunc func() T, elseFunc func() T) T { + if condition { + return ifFunc() + } + + return elseFunc() +} + +type ifElse[T any] struct { + result T + done bool +} + +// If. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func If[T any](condition bool, result T) *ifElse[T] { + if condition { + return &ifElse[T]{result, true} + } + + var t T + return &ifElse[T]{t, false} +} + +// IfF. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func IfF[T any](condition bool, resultF func() T) *ifElse[T] { + if condition { + return &ifElse[T]{resultF(), true} + } + + var t T + return &ifElse[T]{t, false} +} + +// ElseIf. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func (i *ifElse[T]) ElseIf(condition bool, result T) *ifElse[T] { + if !i.done && condition { + i.result = result + i.done = true + } + + return i +} + +// ElseIfF. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func (i *ifElse[T]) ElseIfF(condition bool, resultF func() T) *ifElse[T] { + if !i.done && condition { + i.result = resultF() + i.done = true + } + + return i +} + +// Else. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func (i *ifElse[T]) Else(result T) T { + if i.done { + return i.result + } + + return result +} + +// ElseF. +// Play: https://go.dev/play/p/WSw3ApMxhyW +func (i *ifElse[T]) ElseF(resultF func() T) T { + if i.done { + return i.result + } + + return resultF() +} + +type switchCase[T comparable, R any] struct { + predicate T + result R + done bool +} + +// Switch is a pure functional switch/case/default statement. +// Play: https://go.dev/play/p/TGbKUMAeRUd +func Switch[T comparable, R any](predicate T) *switchCase[T, R] { + var result R + + return &switchCase[T, R]{ + predicate, + result, + false, + } +} + +// Case. +// Play: https://go.dev/play/p/TGbKUMAeRUd +func (s *switchCase[T, R]) Case(val T, result R) *switchCase[T, R] { + if !s.done && s.predicate == val { + s.result = result + s.done = true + } + + return s +} + +// CaseF. +// Play: https://go.dev/play/p/TGbKUMAeRUd +func (s *switchCase[T, R]) CaseF(val T, cb func() R) *switchCase[T, R] { + if !s.done && s.predicate == val { + s.result = cb() + s.done = true + } + + return s +} + +// Default. +// Play: https://go.dev/play/p/TGbKUMAeRUd +func (s *switchCase[T, R]) Default(result R) R { + if !s.done { + s.result = result + } + + return s.result +} + +// DefaultF. +// Play: https://go.dev/play/p/TGbKUMAeRUd +func (s *switchCase[T, R]) DefaultF(cb func() R) R { + if !s.done { + s.result = cb() + } + + return s.result +} diff --git a/vendor/github.com/samber/lo/constraints.go b/vendor/github.com/samber/lo/constraints.go new file mode 100644 index 0000000000..c1f3529685 --- /dev/null +++ b/vendor/github.com/samber/lo/constraints.go @@ -0,0 +1,6 @@ +package lo + +// Clonable defines a constraint of types having Clone() T method. +type Clonable[T any] interface { + Clone() T +} diff --git a/vendor/github.com/samber/lo/errors.go b/vendor/github.com/samber/lo/errors.go new file mode 100644 index 0000000000..a2347218dc --- /dev/null +++ b/vendor/github.com/samber/lo/errors.go @@ -0,0 +1,381 @@ +package lo + +import ( + "errors" + "fmt" + "reflect" +) + +const defaultAssertionFailureMessage = "assertion failed" + +// Validate is a helper that creates an error when a condition is not met. +// Play: https://go.dev/play/p/vPyh51XpCBt +func Validate(ok bool, format string, args ...any) error { + if !ok { + return fmt.Errorf(format, args...) + } + return nil +} + +func messageFromMsgAndArgs(msgAndArgs ...any) string { + if len(msgAndArgs) == 1 { + if msgAsStr, ok := msgAndArgs[0].(string); ok { + return msgAsStr + } + return fmt.Sprintf("%+v", msgAndArgs[0]) + } + if len(msgAndArgs) > 1 { + return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) + } + return "" +} + +// must panics if err is error or false. +func must(err any, messageArgs ...any) { + if err == nil { + return + } + + switch e := err.(type) { + case bool: + if !e { + message := messageFromMsgAndArgs(messageArgs...) + if message == "" { + message = "not ok" + } + + panic(message) + } + + case error: + message := messageFromMsgAndArgs(messageArgs...) + if message != "" { + panic(message + ": " + e.Error()) + } else { + panic(e.Error()) + } + + default: + panic("must: invalid err type '" + reflect.TypeOf(err).Name() + "', should either be a bool or an error") + } +} + +// Must is a helper that wraps a call to a function returning a value and an error +// and panics if err is error or false. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must[T any](val T, err any, messageArgs ...any) T { + must(err, messageArgs...) + return val +} + +// Must0 has the same behavior as Must, but callback returns no variable. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must0(err any, messageArgs ...any) { + must(err, messageArgs...) +} + +// Must1 is an alias to Must +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must1[T any](val T, err any, messageArgs ...any) T { + return Must(val, err, messageArgs...) +} + +// Must2 has the same behavior as Must, but callback returns 2 variables. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must2[T1, T2 any](val1 T1, val2 T2, err any, messageArgs ...any) (T1, T2) { + must(err, messageArgs...) + return val1, val2 +} + +// Must3 has the same behavior as Must, but callback returns 3 variables. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must3[T1, T2, T3 any](val1 T1, val2 T2, val3 T3, err any, messageArgs ...any) (T1, T2, T3) { + must(err, messageArgs...) + return val1, val2, val3 +} + +// Must4 has the same behavior as Must, but callback returns 4 variables. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must4[T1, T2, T3, T4 any](val1 T1, val2 T2, val3 T3, val4 T4, err any, messageArgs ...any) (T1, T2, T3, T4) { + must(err, messageArgs...) + return val1, val2, val3, val4 +} + +// Must5 has the same behavior as Must, but callback returns 5 variables. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must5[T1, T2, T3, T4, T5 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, err any, messageArgs ...any) (T1, T2, T3, T4, T5) { + must(err, messageArgs...) + return val1, val2, val3, val4, val5 +} + +// Must6 has the same behavior as Must, but callback returns 6 variables. +// Play: https://go.dev/play/p/TMoWrRp3DyC +func Must6[T1, T2, T3, T4, T5, T6 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, val6 T6, err any, messageArgs ...any) (T1, T2, T3, T4, T5, T6) { + must(err, messageArgs...) + return val1, val2, val3, val4, val5, val6 +} + +// Try calls the function and return false in case of error. +func Try(callback func() error) (ok bool) { + ok = true + + defer func() { + if r := recover(); r != nil { + ok = false + } + }() + + err := callback() + if err != nil { + ok = false + } + + return +} + +// Try0 has the same behavior as Try, but callback returns no variable. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try0(callback func()) bool { + return Try(func() error { + callback() + return nil + }) +} + +// Try1 is an alias to Try. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try1(callback func() error) bool { + return Try(callback) +} + +// Try2 has the same behavior as Try, but callback returns 2 variables. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try2[T any](callback func() (T, error)) bool { + return Try(func() error { + _, err := callback() + return err + }) +} + +// Try3 has the same behavior as Try, but callback returns 3 variables. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try3[T, R any](callback func() (T, R, error)) bool { + return Try(func() error { + _, _, err := callback() + return err + }) +} + +// Try4 has the same behavior as Try, but callback returns 4 variables. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try4[T, R, S any](callback func() (T, R, S, error)) bool { + return Try(func() error { + _, _, _, err := callback() + return err + }) +} + +// Try5 has the same behavior as Try, but callback returns 5 variables. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try5[T, R, S, Q any](callback func() (T, R, S, Q, error)) bool { + return Try(func() error { + _, _, _, _, err := callback() + return err + }) +} + +// Try6 has the same behavior as Try, but callback returns 6 variables. +// Play: https://go.dev/play/p/mTyyWUvn9u4 +func Try6[T, R, S, Q, U any](callback func() (T, R, S, Q, U, error)) bool { + return Try(func() error { + _, _, _, _, _, err := callback() + return err + }) +} + +// TryOr has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr[A any](callback func() (A, error), fallbackA A) (A, bool) { + return TryOr1(callback, fallbackA) +} + +// TryOr1 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr1[A any](callback func() (A, error), fallbackA A) (A, bool) { + ok := false + + Try0(func() { + a, err := callback() + if err == nil { + fallbackA = a + ok = true + } + }) + + return fallbackA, ok +} + +// TryOr2 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr2[A, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) { + ok := false + + Try0(func() { + a, b, err := callback() + if err == nil { + fallbackA = a + fallbackB = b + ok = true + } + }) + + return fallbackA, fallbackB, ok +} + +// TryOr3 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr3[A, B, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) { + ok := false + + Try0(func() { + a, b, c, err := callback() + if err == nil { + fallbackA = a + fallbackB = b + fallbackC = c + ok = true + } + }) + + return fallbackA, fallbackB, fallbackC, ok +} + +// TryOr4 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr4[A, B, C, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D) (A, B, C, D, bool) { + ok := false + + Try0(func() { + a, b, c, d, err := callback() + if err == nil { + fallbackA = a + fallbackB = b + fallbackC = c + fallbackD = d + ok = true + } + }) + + return fallbackA, fallbackB, fallbackC, fallbackD, ok +} + +// TryOr5 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr5[A, B, C, D, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E) (A, B, C, D, E, bool) { + ok := false + + Try0(func() { + a, b, c, d, e, err := callback() + if err == nil { + fallbackA = a + fallbackB = b + fallbackC = c + fallbackD = d + fallbackE = e + ok = true + } + }) + + return fallbackA, fallbackB, fallbackC, fallbackD, fallbackE, ok +} + +// TryOr6 has the same behavior as Must, but returns a default value in case of error. +// Play: https://go.dev/play/p/B4F7Wg2Zh9X +func TryOr6[A, B, C, D, E, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E, fallbackF F) (A, B, C, D, E, F, bool) { + ok := false + + Try0(func() { + a, b, c, d, e, f, err := callback() + if err == nil { + fallbackA = a + fallbackB = b + fallbackC = c + fallbackD = d + fallbackE = e + fallbackF = f + ok = true + } + }) + + return fallbackA, fallbackB, fallbackC, fallbackD, fallbackE, fallbackF, ok +} + +// TryWithErrorValue has the same behavior as Try, but also returns value passed to panic. +// Play: https://go.dev/play/p/Kc7afQIT2Fs +func TryWithErrorValue(callback func() error) (errorValue any, ok bool) { + ok = true + + defer func() { + if r := recover(); r != nil { + ok = false + errorValue = r + } + }() + + err := callback() + if err != nil { + ok = false + errorValue = err + } + + return +} + +// TryCatch has the same behavior as Try, but calls the catch function in case of error. +// Play: https://go.dev/play/p/PnOON-EqBiU +func TryCatch(callback func() error, catch func()) { + if !Try(callback) { + catch() + } +} + +// TryCatchWithErrorValue has the same behavior as TryWithErrorValue, but calls the catch function in case of error. +// Play: https://go.dev/play/p/8Pc9gwX_GZO +func TryCatchWithErrorValue(callback func() error, catch func(any)) { + if err, ok := TryWithErrorValue(callback); !ok { + catch(err) + } +} + +// ErrorsAs is a shortcut for errors.As(err, &&T). +// Play: https://go.dev/play/p/8wk5rH8UfrE +func ErrorsAs[T error](err error) (T, bool) { + var t T + ok := errors.As(err, &t) + return t, ok +} + +// Assert does nothing when the condition is true, otherwise it panics with an optional message. +// Play: https://go.dev/play/p/Xv8LLKBMNwI +func Assert(condition bool, message ...string) { + if condition { + return + } + + panicMessage := defaultAssertionFailureMessage + if len(message) > 0 { + panicMessage = fmt.Sprintf("%s: %s", defaultAssertionFailureMessage, message[0]) + } + panic(panicMessage) +} + +// Assertf does nothing when the condition is true, otherwise it panics with a formatted message. +// Play: https://go.dev/play/p/TVPEmVcyrdY +func Assertf(condition bool, format string, args ...any) { + if condition { + return + } + + panicMessage := fmt.Sprintf("%s: %s", defaultAssertionFailureMessage, fmt.Sprintf(format, args...)) + panic(panicMessage) +} diff --git a/vendor/github.com/samber/lo/find.go b/vendor/github.com/samber/lo/find.go new file mode 100644 index 0000000000..f04dc082ee --- /dev/null +++ b/vendor/github.com/samber/lo/find.go @@ -0,0 +1,651 @@ +package lo + +import ( + "fmt" + "time" + + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/internal/rand" +) + +// IndexOf returns the index at which the first occurrence of a value is found in an array or return -1 +// if the value cannot be found. +func IndexOf[T comparable](collection []T, element T) int { + for i := range collection { + if collection[i] == element { + return i + } + } + + return -1 +} + +// LastIndexOf returns the index at which the last occurrence of a value is found in an array or return -1 +// if the value cannot be found. +func LastIndexOf[T comparable](collection []T, element T) int { + length := len(collection) + + for i := length - 1; i >= 0; i-- { + if collection[i] == element { + return i + } + } + + return -1 +} + +// Find search an element in a slice based on a predicate. It returns element and true if element was found. +func Find[T any](collection []T, predicate func(item T) bool) (T, bool) { + for i := range collection { + if predicate(collection[i]) { + return collection[i], true + } + } + + var result T + return result, false +} + +// FindIndexOf searches an element in a slice based on a predicate and returns the index and true. +// It returns -1 and false if the element is not found. +func FindIndexOf[T any](collection []T, predicate func(item T) bool) (T, int, bool) { + for i := range collection { + if predicate(collection[i]) { + return collection[i], i, true + } + } + + var result T + return result, -1, false +} + +// FindLastIndexOf searches last element in a slice based on a predicate and returns the index and true. +// It returns -1 and false if the element is not found. +func FindLastIndexOf[T any](collection []T, predicate func(item T) bool) (T, int, bool) { + length := len(collection) + + for i := length - 1; i >= 0; i-- { + if predicate(collection[i]) { + return collection[i], i, true + } + } + + var result T + return result, -1, false +} + +// FindOrElse search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. +func FindOrElse[T any](collection []T, fallback T, predicate func(item T) bool) T { + for i := range collection { + if predicate(collection[i]) { + return collection[i] + } + } + + return fallback +} + +// FindKey returns the key of the first value matching. +func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool) { + for k := range object { + if object[k] == value { + return k, true + } + } + + return Empty[K](), false +} + +// FindKeyBy returns the key of the first element predicate returns truthy for. +func FindKeyBy[K comparable, V any](object map[K]V, predicate func(key K, value V) bool) (K, bool) { + for k := range object { + if predicate(k, object[k]) { + return k, true + } + } + + return Empty[K](), false +} + +// FindUniques returns a slice with all the unique elements of the collection. +// The order of result values is determined by the order they occur in the collection. +func FindUniques[T comparable, Slice ~[]T](collection Slice) Slice { + isDupl := make(map[T]bool, len(collection)) + + for i := range collection { + duplicated, ok := isDupl[collection[i]] + if !ok { + isDupl[collection[i]] = false + } else if !duplicated { + isDupl[collection[i]] = true + } + } + + result := make(Slice, 0, len(collection)-len(isDupl)) + + for i := range collection { + if duplicated := isDupl[collection[i]]; !duplicated { + result = append(result, collection[i]) + } + } + + return result +} + +// FindUniquesBy returns a slice with all the unique elements of the collection. +// The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is +// invoked for each element in array to generate the criterion by which uniqueness is computed. +func FindUniquesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { + isDupl := make(map[U]bool, len(collection)) + + for i := range collection { + key := iteratee(collection[i]) + + duplicated, ok := isDupl[key] + if !ok { + isDupl[key] = false + } else if !duplicated { + isDupl[key] = true + } + } + + result := make(Slice, 0, len(collection)-len(isDupl)) + + for i := range collection { + key := iteratee(collection[i]) + + if duplicated := isDupl[key]; !duplicated { + result = append(result, collection[i]) + } + } + + return result +} + +// FindDuplicates returns a slice with the first occurrence of each duplicated elements of the collection. +// The order of result values is determined by the order they occur in the collection. +func FindDuplicates[T comparable, Slice ~[]T](collection Slice) Slice { + isDupl := make(map[T]bool, len(collection)) + + for i := range collection { + duplicated, ok := isDupl[collection[i]] + if !ok { + isDupl[collection[i]] = false + } else if !duplicated { + isDupl[collection[i]] = true + } + } + + result := make(Slice, 0, len(collection)-len(isDupl)) + + for i := range collection { + if duplicated := isDupl[collection[i]]; duplicated { + result = append(result, collection[i]) + isDupl[collection[i]] = false + } + } + + return result +} + +// FindDuplicatesBy returns a slice with the first occurrence of each duplicated elements of the collection. +// The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is +// invoked for each element in array to generate the criterion by which uniqueness is computed. +func FindDuplicatesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { + isDupl := make(map[U]bool, len(collection)) + + for i := range collection { + key := iteratee(collection[i]) + + duplicated, ok := isDupl[key] + if !ok { + isDupl[key] = false + } else if !duplicated { + isDupl[key] = true + } + } + + result := make(Slice, 0, len(collection)-len(isDupl)) + + for i := range collection { + key := iteratee(collection[i]) + + if duplicated := isDupl[key]; duplicated { + result = append(result, collection[i]) + isDupl[key] = false + } + } + + return result +} + +// Min search the minimum value of a collection. +// Returns zero value when the collection is empty. +func Min[T constraints.Ordered](collection []T) T { + var min T + + if len(collection) == 0 { + return min + } + + min = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if item < min { + min = item + } + } + + return min +} + +// MinIndex search the minimum value of a collection and the index of the minimum value. +// Returns (zero value, -1) when the collection is empty. +func MinIndex[T constraints.Ordered](collection []T) (T, int) { + var ( + min T + index int + ) + + if len(collection) == 0 { + return min, -1 + } + + min = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if item < min { + min = item + index = i + } + } + + return min, index +} + +// MinBy search the minimum value of a collection using the given comparison function. +// If several values of the collection are equal to the smallest value, returns the first such value. +// Returns zero value when the collection is empty. +func MinBy[T any](collection []T, comparison func(a T, b T) bool) T { + var min T + + if len(collection) == 0 { + return min + } + + min = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if comparison(item, min) { + min = item + } + } + + return min +} + +// MinIndexBy search the minimum value of a collection using the given comparison function and the index of the minimum value. +// If several values of the collection are equal to the smallest value, returns the first such value. +// Returns (zero value, -1) when the collection is empty. +func MinIndexBy[T any](collection []T, comparison func(a T, b T) bool) (T, int) { + var ( + min T + index int + ) + + if len(collection) == 0 { + return min, -1 + } + + min = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if comparison(item, min) { + min = item + index = i + } + } + + return min, index +} + +// Earliest search the minimum time.Time of a collection. +// Returns zero value when the collection is empty. +func Earliest(times ...time.Time) time.Time { + var min time.Time + + if len(times) == 0 { + return min + } + + min = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.Before(min) { + min = item + } + } + + return min +} + +// EarliestBy search the minimum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func EarliestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var earliest T + + if len(collection) == 0 { + return earliest + } + + earliest = collection[0] + earliestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.Before(earliestTime) { + earliest = collection[i] + earliestTime = itemTime + } + } + + return earliest +} + +// Max searches the maximum value of a collection. +// Returns zero value when the collection is empty. +func Max[T constraints.Ordered](collection []T) T { + var max T + + if len(collection) == 0 { + return max + } + + max = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if item > max { + max = item + } + } + + return max +} + +// MaxIndex searches the maximum value of a collection and the index of the maximum value. +// Returns (zero value, -1) when the collection is empty. +func MaxIndex[T constraints.Ordered](collection []T) (T, int) { + var ( + max T + index int + ) + + if len(collection) == 0 { + return max, -1 + } + + max = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if item > max { + max = item + index = i + } + } + + return max, index +} + +// MaxBy search the maximum value of a collection using the given comparison function. +// If several values of the collection are equal to the greatest value, returns the first such value. +// Returns zero value when the collection is empty. +func MaxBy[T any](collection []T, comparison func(a T, b T) bool) T { + var max T + + if len(collection) == 0 { + return max + } + + max = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if comparison(item, max) { + max = item + } + } + + return max +} + +// MaxIndexBy search the maximum value of a collection using the given comparison function and the index of the maximum value. +// If several values of the collection are equal to the greatest value, returns the first such value. +// Returns (zero value, -1) when the collection is empty. +func MaxIndexBy[T any](collection []T, comparison func(a T, b T) bool) (T, int) { + var ( + max T + index int + ) + + if len(collection) == 0 { + return max, -1 + } + + max = collection[0] + + for i := 1; i < len(collection); i++ { + item := collection[i] + + if comparison(item, max) { + max = item + index = i + } + } + + return max, index +} + +// Latest search the maximum time.Time of a collection. +// Returns zero value when the collection is empty. +func Latest(times ...time.Time) time.Time { + var max time.Time + + if len(times) == 0 { + return max + } + + max = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.After(max) { + max = item + } + } + + return max +} + +// LatestBy search the maximum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func LatestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var latest T + + if len(collection) == 0 { + return latest + } + + latest = collection[0] + latestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.After(latestTime) { + latest = collection[i] + latestTime = itemTime + } + } + + return latest +} + +// First returns the first element of a collection and check for availability of the first element. +func First[T any](collection []T) (T, bool) { + length := len(collection) + + if length == 0 { + var t T + return t, false + } + + return collection[0], true +} + +// FirstOrEmpty returns the first element of a collection or zero value if empty. +func FirstOrEmpty[T any](collection []T) T { + i, _ := First(collection) + return i +} + +// FirstOr returns the first element of a collection or the fallback value if empty. +func FirstOr[T any](collection []T, fallback T) T { + i, ok := First(collection) + if !ok { + return fallback + } + + return i +} + +// Last returns the last element of a collection or error if empty. +func Last[T any](collection []T) (T, bool) { + length := len(collection) + + if length == 0 { + var t T + return t, false + } + + return collection[length-1], true +} + +// LastOrEmpty returns the last element of a collection or zero value if empty. +func LastOrEmpty[T any](collection []T) T { + i, _ := Last(collection) + return i +} + +// LastOr returns the last element of a collection or the fallback value if empty. +func LastOr[T any](collection []T, fallback T) T { + i, ok := Last(collection) + if !ok { + return fallback + } + + return i +} + +// Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element +// from the end is returned. An error is returned when nth is out of slice bounds. +func Nth[T any, N constraints.Integer](collection []T, nth N) (T, error) { + n := int(nth) + l := len(collection) + if n >= l || -n > l { + var t T + return t, fmt.Errorf("nth: %d out of slice bounds", n) + } + + if n >= 0 { + return collection[n], nil + } + return collection[l+n], nil +} + +// NthOr returns the element at index `nth` of collection. +// If `nth` is negative, it returns the nth element from the end. +// If `nth` is out of slice bounds, it returns the fallback value instead of an error. +func NthOr[T any, N constraints.Integer](collection []T, nth N, fallback T) T { + value, err := Nth(collection, nth) + if err != nil { + return fallback + } + return value +} + +// NthOrEmpty returns the element at index `nth` of collection. +// If `nth` is negative, it returns the nth element from the end. +// If `nth` is out of slice bounds, it returns the zero value (empty value) for that type. +func NthOrEmpty[T any, N constraints.Integer](collection []T, nth N) T { + value, err := Nth(collection, nth) + if err != nil { + var zeroValue T + return zeroValue + } + return value +} + +// randomIntGenerator is a function that should return a random integer in the range [0, n) +// where n is the parameter passed to the randomIntGenerator. +type randomIntGenerator func(n int) int + +// Sample returns a random item from collection. +func Sample[T any](collection []T) T { + result := SampleBy(collection, rand.IntN) + return result +} + +// SampleBy returns a random item from collection, using randomIntGenerator as the random index generator. +func SampleBy[T any](collection []T, randomIntGenerator randomIntGenerator) T { + size := len(collection) + if size == 0 { + return Empty[T]() + } + return collection[randomIntGenerator(size)] +} + +// Samples returns N random unique items from collection. +func Samples[T any, Slice ~[]T](collection Slice, count int) Slice { + results := SamplesBy(collection, count, rand.IntN) + return results +} + +// SamplesBy returns N random unique items from collection, using randomIntGenerator as the random index generator. +func SamplesBy[T any, Slice ~[]T](collection Slice, count int, randomIntGenerator randomIntGenerator) Slice { + size := len(collection) + + copy := append(Slice{}, collection...) + + results := Slice{} + + for i := 0; i < size && i < count; i++ { + copyLength := size - i + + index := randomIntGenerator(size - i) + results = append(results, copy[index]) + + // Removes element. + // It is faster to swap with last element and remove it. + copy[index] = copy[copyLength-1] + copy = copy[:copyLength-1] + } + + return results +} diff --git a/vendor/github.com/samber/lo/func.go b/vendor/github.com/samber/lo/func.go new file mode 100644 index 0000000000..5fa1cbc871 --- /dev/null +++ b/vendor/github.com/samber/lo/func.go @@ -0,0 +1,41 @@ +package lo + +// Partial returns new function that, when called, has its first argument set to the provided value. +func Partial[T1, T2, R any](f func(a T1, b T2) R, arg1 T1) func(T2) R { + return func(t2 T2) R { + return f(arg1, t2) + } +} + +// Partial1 returns new function that, when called, has its first argument set to the provided value. +func Partial1[T1, T2, R any](f func(T1, T2) R, arg1 T1) func(T2) R { + return Partial(f, arg1) +} + +// Partial2 returns new function that, when called, has its first argument set to the provided value. +func Partial2[T1, T2, T3, R any](f func(T1, T2, T3) R, arg1 T1) func(T2, T3) R { + return func(t2 T2, t3 T3) R { + return f(arg1, t2, t3) + } +} + +// Partial3 returns new function that, when called, has its first argument set to the provided value. +func Partial3[T1, T2, T3, T4, R any](f func(T1, T2, T3, T4) R, arg1 T1) func(T2, T3, T4) R { + return func(t2 T2, t3 T3, t4 T4) R { + return f(arg1, t2, t3, t4) + } +} + +// Partial4 returns new function that, when called, has its first argument set to the provided value. +func Partial4[T1, T2, T3, T4, T5, R any](f func(T1, T2, T3, T4, T5) R, arg1 T1) func(T2, T3, T4, T5) R { + return func(t2 T2, t3 T3, t4 T4, t5 T5) R { + return f(arg1, t2, t3, t4, t5) + } +} + +// Partial5 returns new function that, when called, has its first argument set to the provided value +func Partial5[T1, T2, T3, T4, T5, T6, R any](f func(T1, T2, T3, T4, T5, T6) R, arg1 T1) func(T2, T3, T4, T5, T6) R { + return func(t2 T2, t3 T3, t4 T4, t5 T5, t6 T6) R { + return f(arg1, t2, t3, t4, t5, t6) + } +} diff --git a/vendor/github.com/samber/lo/internal/constraints/constraints.go b/vendor/github.com/samber/lo/internal/constraints/constraints.go new file mode 100644 index 0000000000..3eb1cda55f --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/constraints.go @@ -0,0 +1,42 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package constraints defines a set of useful constraints to be used +// with type parameters. +package constraints + +// Signed is a constraint that permits any signed integer type. +// If future releases of Go add new predeclared signed integer types, +// this constraint will be modified to include them. +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// Unsigned is a constraint that permits any unsigned integer type. +// If future releases of Go add new predeclared unsigned integer types, +// this constraint will be modified to include them. +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +// Integer is a constraint that permits any integer type. +// If future releases of Go add new predeclared integer types, +// this constraint will be modified to include them. +type Integer interface { + Signed | Unsigned +} + +// Float is a constraint that permits any floating-point type. +// If future releases of Go add new predeclared floating-point types, +// this constraint will be modified to include them. +type Float interface { + ~float32 | ~float64 +} + +// Complex is a constraint that permits any complex numeric type. +// If future releases of Go add new predeclared complex numeric types, +// this constraint will be modified to include them. +type Complex interface { + ~complex64 | ~complex128 +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go new file mode 100644 index 0000000000..a124366fd3 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go @@ -0,0 +1,11 @@ +//go:build !go1.21 + +package constraints + +// Ordered is a constraint that permits any ordered type: any type +// that supports the operators < <= >= >. +// If future releases of Go add new ordered types, +// this constraint will be modified to include them. +type Ordered interface { + Integer | Float | ~string +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go new file mode 100644 index 0000000000..c02de93548 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go @@ -0,0 +1,9 @@ +//go:build go1.21 + +package constraints + +import ( + "cmp" +) + +type Ordered = cmp.Ordered diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go118.go b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go new file mode 100644 index 0000000000..9fbc5385a0 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go @@ -0,0 +1,26 @@ +//go:build !go1.22 + +package rand + +import "math/rand" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + // bearer:disable go_gosec_crypto_weak_random + return rand.Intn(n) +} + +func Int64() int64 { + // bearer:disable go_gosec_crypto_weak_random + n := rand.Int63() + + // bearer:disable go_gosec_crypto_weak_random + if rand.Intn(2) == 0 { + return -n + } + + return n +} diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go122.go b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go new file mode 100644 index 0000000000..65abf51a7a --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go @@ -0,0 +1,17 @@ +//go:build go1.22 + +package rand + +import "math/rand/v2" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + return rand.IntN(n) +} + +func Int64() int64 { + return rand.Int64() +} diff --git a/vendor/github.com/samber/lo/intersect.go b/vendor/github.com/samber/lo/intersect.go new file mode 100644 index 0000000000..c57bd81719 --- /dev/null +++ b/vendor/github.com/samber/lo/intersect.go @@ -0,0 +1,265 @@ +package lo + +// Contains returns true if an element is present in a collection. +func Contains[T comparable](collection []T, element T) bool { + for i := range collection { + if collection[i] == element { + return true + } + } + + return false +} + +// ContainsBy returns true if predicate function return true. +func ContainsBy[T any](collection []T, predicate func(item T) bool) bool { + for i := range collection { + if predicate(collection[i]) { + return true + } + } + + return false +} + +// Every returns true if all elements of a subset are contained into a collection or if the subset is empty. +func Every[T comparable](collection []T, subset []T) bool { + for i := range subset { + if !Contains(collection, subset[i]) { + return false + } + } + + return true +} + +// EveryBy returns true if the predicate returns true for all elements in the collection or if the collection is empty. +func EveryBy[T any](collection []T, predicate func(item T) bool) bool { + for i := range collection { + if !predicate(collection[i]) { + return false + } + } + + return true +} + +// Some returns true if at least 1 element of a subset is contained into a collection. +// If the subset is empty Some returns false. +func Some[T comparable](collection []T, subset []T) bool { + for i := range subset { + if Contains(collection, subset[i]) { + return true + } + } + + return false +} + +// SomeBy returns true if the predicate returns true for any of the elements in the collection. +// If the collection is empty SomeBy returns false. +func SomeBy[T any](collection []T, predicate func(item T) bool) bool { + for i := range collection { + if predicate(collection[i]) { + return true + } + } + + return false +} + +// None returns true if no element of a subset are contained into a collection or if the subset is empty. +func None[T comparable](collection []T, subset []T) bool { + for i := range subset { + if Contains(collection, subset[i]) { + return false + } + } + + return true +} + +// NoneBy returns true if the predicate returns true for none of the elements in the collection or if the collection is empty. +func NoneBy[T any](collection []T, predicate func(item T) bool) bool { + for i := range collection { + if predicate(collection[i]) { + return false + } + } + + return true +} + +// Intersect returns the intersection between two collections. +func Intersect[T comparable, Slice ~[]T](list1 Slice, list2 Slice) Slice { + result := Slice{} + seen := map[T]struct{}{} + + for i := range list1 { + seen[list1[i]] = struct{}{} + } + + for i := range list2 { + if _, ok := seen[list2[i]]; ok { + result = append(result, list2[i]) + } + } + + return result +} + +// Difference returns the difference between two collections. +// The first value is the collection of element absent of list2. +// The second value is the collection of element absent of list1. +func Difference[T comparable, Slice ~[]T](list1 Slice, list2 Slice) (Slice, Slice) { + left := Slice{} + right := Slice{} + + seenLeft := map[T]struct{}{} + seenRight := map[T]struct{}{} + + for i := range list1 { + seenLeft[list1[i]] = struct{}{} + } + + for i := range list2 { + seenRight[list2[i]] = struct{}{} + } + + for i := range list1 { + if _, ok := seenRight[list1[i]]; !ok { + left = append(left, list1[i]) + } + } + + for i := range list2 { + if _, ok := seenLeft[list2[i]]; !ok { + right = append(right, list2[i]) + } + } + + return left, right +} + +// Union returns all distinct elements from given collections. +// result returns will not change the order of elements relatively. +func Union[T comparable, Slice ~[]T](lists ...Slice) Slice { + var capLen int + + for _, list := range lists { + capLen += len(list) + } + + result := make(Slice, 0, capLen) + seen := make(map[T]struct{}, capLen) + + for i := range lists { + for j := range lists[i] { + if _, ok := seen[lists[i][j]]; !ok { + seen[lists[i][j]] = struct{}{} + result = append(result, lists[i][j]) + } + } + } + + return result +} + +// Without returns slice excluding all given values. +func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice { + excludeMap := make(map[T]struct{}, len(exclude)) + for i := range exclude { + excludeMap[exclude[i]] = struct{}{} + } + + result := make(Slice, 0, len(collection)) + for i := range collection { + if _, ok := excludeMap[collection[i]]; !ok { + result = append(result, collection[i]) + } + } + return result +} + +// WithoutBy filters a slice by excluding elements whose extracted keys match any in the exclude list. +// It returns a new slice containing only the elements whose keys are not in the exclude list. +func WithoutBy[T any, K comparable](collection []T, iteratee func(item T) K, exclude ...K) []T { + excludeMap := make(map[K]struct{}, len(exclude)) + for _, e := range exclude { + excludeMap[e] = struct{}{} + } + + result := make([]T, 0, len(collection)) + for _, item := range collection { + if _, ok := excludeMap[iteratee(item)]; !ok { + result = append(result, item) + } + } + return result +} + +// WithoutEmpty returns slice excluding zero values. +// +// Deprecated: Use lo.Compact instead. +func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice { + return Compact(collection) +} + +// WithoutNth returns slice excluding nth value. +func WithoutNth[T comparable, Slice ~[]T](collection Slice, nths ...int) Slice { + length := len(collection) + + toRemove := make(map[int]struct{}, len(nths)) + for i := range nths { + if nths[i] >= 0 && nths[i] <= length-1 { + toRemove[nths[i]] = struct{}{} + } + } + + result := make(Slice, 0, len(collection)) + for i := range collection { + if _, ok := toRemove[i]; !ok { + result = append(result, collection[i]) + } + } + + return result +} + +// ElementsMatch returns true if lists contain the same set of elements (including empty set). +// If there are duplicate elements, the number of appearances of each of them in both lists should match. +// The order of elements is not checked. +func ElementsMatch[T comparable, Slice ~[]T](list1 Slice, list2 Slice) bool { + return ElementsMatchBy(list1, list2, func(item T) T { return item }) +} + +// ElementsMatchBy returns true if lists contain the same set of elements' keys (including empty set). +// If there are duplicate keys, the number of appearances of each of them in both lists should match. +// The order of elements is not checked. +func ElementsMatchBy[T any, K comparable](list1 []T, list2 []T, iteratee func(item T) K) bool { + if len(list1) != len(list2) { + return false + } + + if len(list1) == 0 { + return true + } + + counters := make(map[K]int, len(list1)) + + for _, el := range list1 { + counters[iteratee(el)]++ + } + + for _, el := range list2 { + counters[iteratee(el)]-- + } + + for _, count := range counters { + if count != 0 { + return false + } + } + + return true +} diff --git a/vendor/github.com/samber/lo/map.go b/vendor/github.com/samber/lo/map.go new file mode 100644 index 0000000000..6febb3fddb --- /dev/null +++ b/vendor/github.com/samber/lo/map.go @@ -0,0 +1,344 @@ +package lo + +// Keys creates an array of the map keys. +// Play: https://go.dev/play/p/Uu11fHASqrU +func Keys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]K, 0, size) + + for i := range in { + for k := range in[i] { + result = append(result, k) + } + } + + return result +} + +// UniqKeys creates an array of unique keys in the map. +// Play: https://go.dev/play/p/TPKAb6ILdHk +func UniqKeys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[K]struct{}, size) + result := make([]K, 0) + + for i := range in { + for k := range in[i] { + if _, exists := seen[k]; exists { + continue + } + seen[k] = struct{}{} + result = append(result, k) + } + } + + return result +} + +// HasKey returns whether the given key exists. +// Play: https://go.dev/play/p/aVwubIvECqS +func HasKey[K comparable, V any](in map[K]V, key K) bool { + _, ok := in[key] + return ok +} + +// Values creates an array of the map values. +// Play: https://go.dev/play/p/nnRTQkzQfF6 +func Values[K comparable, V any](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]V, 0, size) + + for i := range in { + for k := range in[i] { + result = append(result, in[i][k]) + } + } + + return result +} + +// UniqValues creates an array of unique values in the map. +// Play: https://go.dev/play/p/nf6bXMh7rM3 +func UniqValues[K comparable, V comparable](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[V]struct{}, size) + result := make([]V, 0) + + for i := range in { + for k := range in[i] { + val := in[i][k] + if _, exists := seen[val]; exists { + continue + } + seen[val] = struct{}{} + result = append(result, val) + } + } + + return result +} + +// ValueOr returns the value of the given key or the fallback value if the key is not present. +// Play: https://go.dev/play/p/bAq9mHErB4V +func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V { + if v, ok := in[key]; ok { + return v + } + return fallback +} + +// PickBy returns same map type filtered by given predicate. +// Play: https://go.dev/play/p/kdg8GR_QMmf +func PickBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if predicate(k, in[k]) { + r[k] = in[k] + } + } + return r +} + +// PickByKeys returns same map type filtered by given keys. +// Play: https://go.dev/play/p/R1imbuci9qU +func PickByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for i := range keys { + if v, ok := in[keys[i]]; ok { + r[keys[i]] = v + } + } + return r +} + +// PickByValues returns same map type filtered by given values. +// Play: https://go.dev/play/p/1zdzSvbfsJc +func PickByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if Contains(values, in[k]) { + r[k] = in[k] + } + } + return r +} + +// OmitBy returns same map type filtered by given predicate. +// Play: https://go.dev/play/p/EtBsR43bdsd +func OmitBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if !predicate(k, in[k]) { + r[k] = in[k] + } + } + return r +} + +// OmitByKeys returns same map type filtered by given keys. +// Play: https://go.dev/play/p/t1QjCrs-ysk +func OmitByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for k := range in { + r[k] = in[k] + } + for i := range keys { + delete(r, keys[i]) + } + return r +} + +// OmitByValues returns same map type filtered by given values. +// Play: https://go.dev/play/p/9UYZi-hrs8j +func OmitByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if !Contains(values, in[k]) { + r[k] = in[k] + } + } + return r +} + +// Entries transforms a map into array of key/value pairs. +// Play: +func Entries[K comparable, V any](in map[K]V) []Entry[K, V] { + entries := make([]Entry[K, V], 0, len(in)) + + for k := range in { + entries = append(entries, Entry[K, V]{ + Key: k, + Value: in[k], + }) + } + + return entries +} + +// ToPairs transforms a map into array of key/value pairs. +// Alias of Entries(). +// Play: https://go.dev/play/p/3Dhgx46gawJ +func ToPairs[K comparable, V any](in map[K]V) []Entry[K, V] { + return Entries(in) +} + +// FromEntries transforms an array of key/value pairs into a map. +// Play: https://go.dev/play/p/oIr5KHFGCEN +func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V { + out := make(map[K]V, len(entries)) + + for i := range entries { + out[entries[i].Key] = entries[i].Value + } + + return out +} + +// FromPairs transforms an array of key/value pairs into a map. +// Alias of FromEntries(). +// Play: https://go.dev/play/p/oIr5KHFGCEN +func FromPairs[K comparable, V any](entries []Entry[K, V]) map[K]V { + return FromEntries(entries) +} + +// Invert creates a map composed of the inverted keys and values. If map +// contains duplicate values, subsequent values overwrite property assignments +// of previous values. +// Play: https://go.dev/play/p/rFQ4rak6iA1 +func Invert[K comparable, V comparable](in map[K]V) map[V]K { + out := make(map[V]K, len(in)) + + for k := range in { + out[in[k]] = k + } + + return out +} + +// Assign merges multiple maps from left to right. +// Play: https://go.dev/play/p/VhwfJOyxf5o +func Assign[K comparable, V any, Map ~map[K]V](maps ...Map) Map { + count := 0 + for i := range maps { + count += len(maps[i]) + } + + out := make(Map, count) + for i := range maps { + for k := range maps[i] { + out[k] = maps[i][k] + } + } + + return out +} + +// ChunkEntries splits a map into an array of elements in groups of a length equal to its size. If the map cannot be split evenly, +// the final chunk will contain the remaining elements. +// Play: https://go.dev/play/p/X_YQL6mmoD- +func ChunkEntries[K comparable, V any](m map[K]V, size int) []map[K]V { + if size <= 0 { + panic("The chunk size must be greater than 0") + } + + count := len(m) + if count == 0 { + return []map[K]V{} + } + + chunksNum := count / size + if count%size != 0 { + chunksNum += 1 + } + + result := make([]map[K]V, 0, chunksNum) + + for k, v := range m { + if len(result) == 0 || len(result[len(result)-1]) == size { + result = append(result, make(map[K]V, size)) + } + + result[len(result)-1][k] = v + } + + return result +} + +// MapKeys manipulates a map keys and transforms it to a map of another type. +// Play: https://go.dev/play/p/9_4WPIqOetJ +func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(value V, key K) R) map[R]V { + result := make(map[R]V, len(in)) + + for k := range in { + result[iteratee(in[k], k)] = in[k] + } + + return result +} + +// MapValues manipulates a map values and transforms it to a map of another type. +// Play: https://go.dev/play/p/T_8xAfvcf0W +func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(value V, key K) R) map[K]R { + result := make(map[K]R, len(in)) + + for k := range in { + result[k] = iteratee(in[k], k) + } + + return result +} + +// MapEntries manipulates a map entries and transforms it to a map of another type. +// Play: https://go.dev/play/p/VuvNQzxKimT +func MapEntries[K1 comparable, V1 any, K2 comparable, V2 any](in map[K1]V1, iteratee func(key K1, value V1) (K2, V2)) map[K2]V2 { + result := make(map[K2]V2, len(in)) + + for k1 := range in { + k2, v2 := iteratee(k1, in[k1]) + result[k2] = v2 + } + + return result +} + +// MapToSlice transforms a map into a slice based on specific iteratee +// Play: https://go.dev/play/p/ZuiCZpDt6LD +func MapToSlice[K comparable, V any, R any](in map[K]V, iteratee func(key K, value V) R) []R { + result := make([]R, 0, len(in)) + + for k := range in { + result = append(result, iteratee(k, in[k])) + } + + return result +} + +// FilterMapToSlice transforms a map into a slice based on specific iteratee. +// The iteratee returns a value and a boolean. If the boolean is true, the value is added to the result slice. +// If the boolean is false, the value is not added to the result slice. +// The order of the keys in the input map is not specified and the order of the keys in the output slice is not guaranteed. +func FilterMapToSlice[K comparable, V any, R any](in map[K]V, iteratee func(key K, value V) (R, bool)) []R { + result := make([]R, 0, len(in)) + + for k := range in { + if v, ok := iteratee(k, in[k]); ok { + result = append(result, v) + } + } + + return result +} diff --git a/vendor/github.com/samber/lo/math.go b/vendor/github.com/samber/lo/math.go new file mode 100644 index 0000000000..e3f4289269 --- /dev/null +++ b/vendor/github.com/samber/lo/math.go @@ -0,0 +1,142 @@ +package lo + +import ( + "github.com/samber/lo/internal/constraints" +) + +// Range creates an array of numbers (positive and/or negative) with given length. +// Play: https://go.dev/play/p/0r6VimXAi9H +func Range(elementNum int) []int { + length := If(elementNum < 0, -elementNum).Else(elementNum) + result := make([]int, length) + step := If(elementNum < 0, -1).Else(1) + for i, j := 0, 0; i < length; i, j = i+1, j+step { + result[i] = j + } + return result +} + +// RangeFrom creates an array of numbers from start with specified length. +// Play: https://go.dev/play/p/0r6VimXAi9H +func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) []T { + length := If(elementNum < 0, -elementNum).Else(elementNum) + result := make([]T, length) + step := If(elementNum < 0, -1).Else(1) + for i, j := 0, start; i < length; i, j = i+1, j+T(step) { + result[i] = j + } + return result +} + +// RangeWithSteps creates an array of numbers (positive and/or negative) progressing from start up to, but not including end. +// step set to zero will return empty array. +// Play: https://go.dev/play/p/0r6VimXAi9H +func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) []T { + result := []T{} + if start == end || step == 0 { + return result + } + if start < end { + if step < 0 { + return result + } + for i := start; i < end; i += step { + result = append(result, i) + } + return result + } + if step > 0 { + return result + } + for i := start; i > end; i += step { + result = append(result, i) + } + return result +} + +// Clamp clamps number within the inclusive lower and upper bounds. +// Play: https://go.dev/play/p/RU4lJNC2hlI +func Clamp[T constraints.Ordered](value T, min T, max T) T { + if value < min { + return min + } else if value > max { + return max + } + return value +} + +// Sum sums the values in a collection. If collection is empty 0 is returned. +// Play: https://go.dev/play/p/upfeJVqs4Bt +func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collection []T) T { + var sum T = 0 + for i := range collection { + sum += collection[i] + } + return sum +} + +// SumBy summarizes the values in a collection using the given return value from the iteration function. If collection is empty 0 is returned. +// Play: https://go.dev/play/p/Dz_a_7jN_ca +func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Complex](collection []T, iteratee func(item T) R) R { + var sum R = 0 + for i := range collection { + sum = sum + iteratee(collection[i]) + } + return sum +} + +// Product gets the product of the values in a collection. If collection is empty 0 is returned. +// Play: https://go.dev/play/p/2_kjM_smtAH +func Product[T constraints.Float | constraints.Integer | constraints.Complex](collection []T) T { + if collection == nil { + return 1 + } + + if len(collection) == 0 { + return 1 + } + + var product T = 1 + for i := range collection { + product *= collection[i] + } + return product +} + +// ProductBy summarizes the values in a collection using the given return value from the iteration function. If collection is empty 0 is returned. +// Play: https://go.dev/play/p/wadzrWr9Aer +func ProductBy[T any, R constraints.Float | constraints.Integer | constraints.Complex](collection []T, iteratee func(item T) R) R { + if collection == nil { + return 1 + } + + if len(collection) == 0 { + return 1 + } + + var product R = 1 + for i := range collection { + product = product * iteratee(collection[i]) + } + return product +} + +// Mean calculates the mean of a collection of numbers. +func Mean[T constraints.Float | constraints.Integer](collection []T) T { + var length = T(len(collection)) + if length == 0 { + return 0 + } + var sum = Sum(collection) + return sum / length +} + +// MeanBy calculates the mean of a collection of numbers using the given return value from the iteration function. +func MeanBy[T any, R constraints.Float | constraints.Integer](collection []T, iteratee func(item T) R) R { + var length = R(len(collection)) + if length == 0 { + return 0 + } + var sum = SumBy(collection, iteratee) + return sum / length +} diff --git a/vendor/github.com/samber/lo/mutable/slice.go b/vendor/github.com/samber/lo/mutable/slice.go new file mode 100644 index 0000000000..969f399553 --- /dev/null +++ b/vendor/github.com/samber/lo/mutable/slice.go @@ -0,0 +1,71 @@ +package mutable + +import "github.com/samber/lo/internal/rand" + +// Filter is a generic function that modifies the input slice in-place to contain only the elements +// that satisfy the provided predicate function. The predicate function takes an element of the slice and its index, +// and should return true for elements that should be kept and false for elements that should be removed. +// The function returns the modified slice, which may be shorter than the original if some elements were removed. +// Note that the order of elements in the original slice is preserved in the output. +func Filter[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { + j := 0 + for _, item := range collection { + if predicate(item) { + collection[j] = item + j++ + } + } + return collection[:j] +} + +// FilterI is a generic function that modifies the input slice in-place to contain only the elements +// that satisfy the provided predicate function. The predicate function takes an element of the slice and its index, +// and should return true for elements that should be kept and false for elements that should be removed. +// The function returns the modified slice, which may be shorter than the original if some elements were removed. +// Note that the order of elements in the original slice is preserved in the output. +func FilterI[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + j := 0 + for i, item := range collection { + if predicate(item, i) { + collection[j] = item + j++ + } + } + return collection[:j] +} + +// Map is a generic function that modifies the input slice in-place to contain the result of applying the provided +// function to each element of the slice. The function returns the modified slice, which has the same length as the original. +func Map[T any, Slice ~[]T](collection Slice, fn func(item T) T) { + for i := range collection { + collection[i] = fn(collection[i]) + } +} + +// MapI is a generic function that modifies the input slice in-place to contain the result of applying the provided +// function to each element of the slice. The function returns the modified slice, which has the same length as the original. +func MapI[T any, Slice ~[]T](collection Slice, fn func(item T, index int) T) { + for i := range collection { + collection[i] = fn(collection[i], i) + } +} + +// Shuffle returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm. +// Play: https://go.dev/play/p/2xb3WdLjeSJ +func Shuffle[T any, Slice ~[]T](collection Slice) { + rand.Shuffle(len(collection), func(i, j int) { + collection[i], collection[j] = collection[j], collection[i] + }) +} + +// Reverse reverses array so that the first element becomes the last, the second element becomes the second to last, and so on. +// Play: https://go.dev/play/p/O-M5pmCRgzV +func Reverse[T any, Slice ~[]T](collection Slice) { + length := len(collection) + half := length / 2 + + for i := 0; i < half; i = i + 1 { + j := length - 1 - i + collection[i], collection[j] = collection[j], collection[i] + } +} diff --git a/vendor/github.com/samber/lo/retry.go b/vendor/github.com/samber/lo/retry.go new file mode 100644 index 0000000000..5b9cef3dd0 --- /dev/null +++ b/vendor/github.com/samber/lo/retry.go @@ -0,0 +1,375 @@ +package lo + +import ( + "sync" + "time" +) + +type debounce struct { + after time.Duration + mu *sync.Mutex + timer *time.Timer + done bool + callbacks []func() +} + +func (d *debounce) reset() { + d.mu.Lock() + defer d.mu.Unlock() + + if d.done { + return + } + + if d.timer != nil { + d.timer.Stop() + } + + d.timer = time.AfterFunc(d.after, func() { + for i := range d.callbacks { + d.callbacks[i]() + } + }) +} + +func (d *debounce) cancel() { + d.mu.Lock() + defer d.mu.Unlock() + + if d.timer != nil { + d.timer.Stop() + d.timer = nil + } + + d.done = true +} + +// NewDebounce creates a debounced instance that delays invoking functions given until after wait milliseconds have elapsed. +// Play: https://go.dev/play/p/mz32VMK2nqe +func NewDebounce(duration time.Duration, f ...func()) (func(), func()) { + d := &debounce{ + after: duration, + mu: new(sync.Mutex), + timer: nil, + done: false, + callbacks: f, + } + + return func() { + d.reset() + }, d.cancel +} + +type debounceByItem struct { + mu *sync.Mutex + timer *time.Timer + count int +} + +type debounceBy[T comparable] struct { + after time.Duration + mu *sync.Mutex + items map[T]*debounceByItem + callbacks []func(key T, count int) +} + +func (d *debounceBy[T]) reset(key T) { + d.mu.Lock() + if _, ok := d.items[key]; !ok { + d.items[key] = &debounceByItem{ + mu: new(sync.Mutex), + timer: nil, + } + } + + item := d.items[key] + + d.mu.Unlock() + + item.mu.Lock() + defer item.mu.Unlock() + + item.count++ + + if item.timer != nil { + item.timer.Stop() + } + + item.timer = time.AfterFunc(d.after, func() { + item.mu.Lock() + count := item.count + item.count = 0 + item.mu.Unlock() + + for i := range d.callbacks { + d.callbacks[i](key, count) + } + }) +} + +func (d *debounceBy[T]) cancel(key T) { + d.mu.Lock() + defer d.mu.Unlock() + + if item, ok := d.items[key]; ok { + item.mu.Lock() + + if item.timer != nil { + item.timer.Stop() + item.timer = nil + } + + item.mu.Unlock() + + delete(d.items, key) + } +} + +// NewDebounceBy creates a debounced instance for each distinct key, that delays invoking functions given until after wait milliseconds have elapsed. +// Play: https://go.dev/play/p/d3Vpt6pxhY8 +func NewDebounceBy[T comparable](duration time.Duration, f ...func(key T, count int)) (func(key T), func(key T)) { + d := &debounceBy[T]{ + after: duration, + mu: new(sync.Mutex), + items: map[T]*debounceByItem{}, + callbacks: f, + } + + return func(key T) { + d.reset(key) + }, d.cancel +} + +// Attempt invokes a function N times until it returns valid output. Returns either the caught error or nil. +// When the first argument is less than `1`, the function runs until a successful response is returned. +// Play: https://go.dev/play/p/3ggJZ2ZKcMj +func Attempt(maxIteration int, f func(index int) error) (int, error) { + var err error + + for i := 0; maxIteration <= 0 || i < maxIteration; i++ { + // for retries >= 0 { + err = f(i) + if err == nil { + return i + 1, nil + } + } + + return maxIteration, err +} + +// AttemptWithDelay invokes a function N times until it returns valid output, +// with a pause between each call. Returns either the caught error or nil. +// When the first argument is less than `1`, the function runs until a successful +// response is returned. +// Play: https://go.dev/play/p/tVs6CygC7m1 +func AttemptWithDelay(maxIteration int, delay time.Duration, f func(index int, duration time.Duration) error) (int, time.Duration, error) { + var err error + + start := time.Now() + + for i := 0; maxIteration <= 0 || i < maxIteration; i++ { + err = f(i, time.Since(start)) + if err == nil { + return i + 1, time.Since(start), nil + } + + if maxIteration <= 0 || i+1 < maxIteration { + time.Sleep(delay) + } + } + + return maxIteration, time.Since(start), err +} + +// AttemptWhile invokes a function N times until it returns valid output. +// Returns either the caught error or nil, along with a bool value to determine +// whether the function should be invoked again. It will terminate the invoke +// immediately if the second return value is false. When the first +// argument is less than `1`, the function runs until a successful response is +// returned. +func AttemptWhile(maxIteration int, f func(int) (error, bool)) (int, error) { + var err error + var shouldContinueInvoke bool + + for i := 0; maxIteration <= 0 || i < maxIteration; i++ { + // for retries >= 0 { + err, shouldContinueInvoke = f(i) + if !shouldContinueInvoke { // if shouldContinueInvoke is false, then return immediately + return i + 1, err + } + if err == nil { + return i + 1, nil + } + } + + return maxIteration, err +} + +// AttemptWhileWithDelay invokes a function N times until it returns valid output, +// with a pause between each call. Returns either the caught error or nil, along +// with a bool value to determine whether the function should be invoked again. +// It will terminate the invoke immediately if the second return value is false. +// When the first argument is less than `1`, the function runs until a successful +// response is returned. +func AttemptWhileWithDelay(maxIteration int, delay time.Duration, f func(int, time.Duration) (error, bool)) (int, time.Duration, error) { + var err error + var shouldContinueInvoke bool + + start := time.Now() + + for i := 0; maxIteration <= 0 || i < maxIteration; i++ { + err, shouldContinueInvoke = f(i, time.Since(start)) + if !shouldContinueInvoke { // if shouldContinueInvoke is false, then return immediately + return i + 1, time.Since(start), err + } + if err == nil { + return i + 1, time.Since(start), nil + } + + if maxIteration <= 0 || i+1 < maxIteration { + time.Sleep(delay) + } + } + + return maxIteration, time.Since(start), err +} + +type transactionStep[T any] struct { + exec func(T) (T, error) + onRollback func(T) T +} + +// NewTransaction instantiate a new transaction. +func NewTransaction[T any]() *Transaction[T] { + return &Transaction[T]{ + steps: []transactionStep[T]{}, + } +} + +// Transaction implements a Saga pattern +type Transaction[T any] struct { + steps []transactionStep[T] +} + +// Then adds a step to the chain of callbacks. It returns the same Transaction. +func (t *Transaction[T]) Then(exec func(T) (T, error), onRollback func(T) T) *Transaction[T] { + t.steps = append(t.steps, transactionStep[T]{ + exec: exec, + onRollback: onRollback, + }) + + return t +} + +// Process runs the Transaction steps and rollbacks in case of errors. +func (t *Transaction[T]) Process(state T) (T, error) { + var i int + var err error + + for i < len(t.steps) { + state, err = t.steps[i].exec(state) + if err != nil { + break + } + + i++ + } + + if err == nil { + return state, nil + } + + for i > 0 { + i-- + state = t.steps[i].onRollback(state) + } + + return state, err +} + +// @TODO: single mutex per key ? +type throttleBy[T comparable] struct { + mu *sync.Mutex + timer *time.Timer + interval time.Duration + callbacks []func(key T) + countLimit int + count map[T]int +} + +func (th *throttleBy[T]) throttledFunc(key T) { + th.mu.Lock() + defer th.mu.Unlock() + + if _, ok := th.count[key]; !ok { + th.count[key] = 0 + } + + if th.count[key] < th.countLimit { + th.count[key]++ + + for _, f := range th.callbacks { + f(key) + } + + } + if th.timer == nil { + th.timer = time.AfterFunc(th.interval, func() { + th.reset() + }) + } +} + +func (th *throttleBy[T]) reset() { + th.mu.Lock() + defer th.mu.Unlock() + + if th.timer != nil { + th.timer.Stop() + } + + th.count = map[T]int{} + th.timer = nil +} + +// NewThrottle creates a throttled instance that invokes given functions only once in every interval. +// This returns 2 functions, First one is throttled function and Second one is a function to reset interval +func NewThrottle(interval time.Duration, f ...func()) (throttle func(), reset func()) { + return NewThrottleWithCount(interval, 1, f...) +} + +// NewThrottleWithCount is NewThrottle with count limit, throttled function will be invoked count times in every interval. +func NewThrottleWithCount(interval time.Duration, count int, f ...func()) (throttle func(), reset func()) { + callbacks := Map(f, func(item func(), _ int) func(struct{}) { + return func(struct{}) { + item() + } + }) + + throttleFn, reset := NewThrottleByWithCount[struct{}](interval, count, callbacks...) + return func() { + throttleFn(struct{}{}) + }, reset +} + +// NewThrottleBy creates a throttled instance that invokes given functions only once in every interval. +// This returns 2 functions, First one is throttled function and Second one is a function to reset interval +func NewThrottleBy[T comparable](interval time.Duration, f ...func(key T)) (throttle func(key T), reset func()) { + return NewThrottleByWithCount[T](interval, 1, f...) +} + +// NewThrottleByWithCount is NewThrottleBy with count limit, throttled function will be invoked count times in every interval. +func NewThrottleByWithCount[T comparable](interval time.Duration, count int, f ...func(key T)) (throttle func(key T), reset func()) { + if count <= 0 { + count = 1 + } + + th := &throttleBy[T]{ + mu: new(sync.Mutex), + interval: interval, + callbacks: f, + countLimit: count, + count: map[T]int{}, + } + return th.throttledFunc, th.reset +} diff --git a/vendor/github.com/samber/lo/slice.go b/vendor/github.com/samber/lo/slice.go new file mode 100644 index 0000000000..9c15a6cb23 --- /dev/null +++ b/vendor/github.com/samber/lo/slice.go @@ -0,0 +1,745 @@ +package lo + +import ( + "sort" + + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/mutable" +) + +// Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for. +// Play: https://go.dev/play/p/Apjg3WeSi7K +func Filter[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := make(Slice, 0, len(collection)) + + for i := range collection { + if predicate(collection[i], i) { + result = append(result, collection[i]) + } + } + + return result +} + +// Map manipulates a slice and transforms it to a slice of another type. +// Play: https://go.dev/play/p/OkPcYAhBo0D +func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { + result := make([]R, len(collection)) + + for i := range collection { + result[i] = iteratee(collection[i], i) + } + + return result +} + +// UniqMap manipulates a slice and transforms it to a slice of another type with unique values. +func UniqMap[T any, R comparable](collection []T, iteratee func(item T, index int) R) []R { + result := make([]R, 0, len(collection)) + seen := make(map[R]struct{}, len(collection)) + + for i := range collection { + r := iteratee(collection[i], i) + if _, ok := seen[r]; !ok { + result = append(result, r) + seen[r] = struct{}{} + } + } + return result +} + +// FilterMap returns a slice which obtained after both filtering and mapping using the given callback function. +// The callback function should return two values: +// - the result of the mapping operation and +// - whether the result element should be included or not. +// +// Play: https://go.dev/play/p/-AuYXfy7opz +func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { + result := make([]R, 0, len(collection)) + + for i := range collection { + if r, ok := callback(collection[i], i); ok { + result = append(result, r) + } + } + + return result +} + +// FlatMap manipulates a slice and transforms and flattens it to a slice of another type. +// The transform function can either return a slice or a `nil`, and in the `nil` case +// no value is added to the final slice. +// Play: https://go.dev/play/p/YSoYmQTA8-U +func FlatMap[T any, R any](collection []T, iteratee func(item T, index int) []R) []R { + result := make([]R, 0, len(collection)) + + for i := range collection { + result = append(result, iteratee(collection[i], i)...) + } + + return result +} + +// Reduce reduces collection to a value which is the accumulated result of running each element in collection +// through accumulator, where each successive invocation is supplied the return value of the previous. +// Play: https://go.dev/play/p/R4UHXZNaaUG +func Reduce[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R { + for i := range collection { + initial = accumulator(initial, collection[i], i) + } + + return initial +} + +// ReduceRight helper is like Reduce except that it iterates over elements of collection from right to left. +// Play: https://go.dev/play/p/Fq3W70l7wXF +func ReduceRight[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R { + for i := len(collection) - 1; i >= 0; i-- { + initial = accumulator(initial, collection[i], i) + } + + return initial +} + +// ForEach iterates over elements of collection and invokes iteratee for each element. +// Play: https://go.dev/play/p/oofyiUPRf8t +func ForEach[T any](collection []T, iteratee func(item T, index int)) { + for i := range collection { + iteratee(collection[i], i) + } +} + +// ForEachWhile iterates over elements of collection and invokes iteratee for each element +// collection return value decide to continue or break, like do while(). +// Play: https://go.dev/play/p/QnLGt35tnow +func ForEachWhile[T any](collection []T, iteratee func(item T, index int) (goon bool)) { + for i := range collection { + if !iteratee(collection[i], i) { + break + } + } +} + +// Times invokes the iteratee n times, returning an array of the results of each invocation. +// The iteratee is invoked with index as argument. +// Play: https://go.dev/play/p/vgQj3Glr6lT +func Times[T any](count int, iteratee func(index int) T) []T { + result := make([]T, count) + + for i := 0; i < count; i++ { + result[i] = iteratee(i) + } + + return result +} + +// Uniq returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. +// The order of result values is determined by the order they occur in the array. +// Play: https://go.dev/play/p/DTzbeXZ6iEN +func Uniq[T comparable, Slice ~[]T](collection Slice) Slice { + result := make(Slice, 0, len(collection)) + seen := make(map[T]struct{}, len(collection)) + + for i := range collection { + if _, ok := seen[collection[i]]; ok { + continue + } + + seen[collection[i]] = struct{}{} + result = append(result, collection[i]) + } + + return result +} + +// UniqBy returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. +// The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is +// invoked for each element in array to generate the criterion by which uniqueness is computed. +// Play: https://go.dev/play/p/g42Z3QSb53u +func UniqBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { + result := make(Slice, 0, len(collection)) + seen := make(map[U]struct{}, len(collection)) + + for i := range collection { + key := iteratee(collection[i]) + + if _, ok := seen[key]; ok { + continue + } + + seen[key] = struct{}{} + result = append(result, collection[i]) + } + + return result +} + +// GroupBy returns an object composed of keys generated from the results of running each element of collection through iteratee. +// Play: https://go.dev/play/p/XnQBd_v6brd +func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) map[U]Slice { + result := map[U]Slice{} + + for i := range collection { + key := iteratee(collection[i]) + + result[key] = append(result[key], collection[i]) + } + + return result +} + +// GroupByMap returns an object composed of keys generated from the results of running each element of collection through iteratee. +func GroupByMap[T any, K comparable, V any](collection []T, iteratee func(item T) (K, V)) map[K][]V { + result := map[K][]V{} + + for i := range collection { + k, v := iteratee(collection[i]) + + result[k] = append(result[k], v) + } + + return result +} + +// Chunk returns an array of elements split into groups the length of size. If array can't be split evenly, +// the final chunk will be the remaining elements. +// Play: https://go.dev/play/p/EeKl0AuTehH +func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { + if size <= 0 { + panic("Second parameter must be greater than 0") + } + + chunksNum := len(collection) / size + if len(collection)%size != 0 { + chunksNum += 1 + } + + result := make([]Slice, 0, chunksNum) + + for i := 0; i < chunksNum; i++ { + last := (i + 1) * size + if last > len(collection) { + last = len(collection) + } + result = append(result, collection[i*size:last:last]) + } + + return result +} + +// PartitionBy returns an array of elements split into groups. The order of grouped values is +// determined by the order they occur in collection. The grouping is generated from the results +// of running each element of collection through iteratee. +// Play: https://go.dev/play/p/NfQ_nGjkgXW +func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice { + result := []Slice{} + seen := map[K]int{} + + for i := range collection { + key := iteratee(collection[i]) + + resultIndex, ok := seen[key] + if !ok { + resultIndex = len(result) + seen[key] = resultIndex + result = append(result, Slice{}) + } + + result[resultIndex] = append(result[resultIndex], collection[i]) + } + + return result + + // unordered: + // groups := GroupBy[T, K](collection, iteratee) + // return Values[K, []T](groups) +} + +// Flatten returns an array a single level deep. +// Play: https://go.dev/play/p/rbp9ORaMpjw +func Flatten[T any, Slice ~[]T](collection []Slice) Slice { + totalLen := 0 + for i := range collection { + totalLen += len(collection[i]) + } + + result := make(Slice, 0, totalLen) + for i := range collection { + result = append(result, collection[i]...) + } + + return result +} + +// Interleave round-robin alternating input slices and sequentially appending value at index into result +// Play: https://go.dev/play/p/-RJkTLQEDVt +func Interleave[T any, Slice ~[]T](collections ...Slice) Slice { + if len(collections) == 0 { + return Slice{} + } + + maxSize := 0 + totalSize := 0 + for i := range collections { + size := len(collections[i]) + totalSize += size + if size > maxSize { + maxSize = size + } + } + + if maxSize == 0 { + return Slice{} + } + + result := make(Slice, totalSize) + + resultIdx := 0 + for i := 0; i < maxSize; i++ { + for j := range collections { + if len(collections[j])-1 < i { + continue + } + + result[resultIdx] = collections[j][i] + resultIdx++ + } + } + + return result +} + +// Shuffle returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm. +// Play: https://go.dev/play/p/ZTGG7OUCdnp +// +// Deprecated: use mutable.Shuffle() instead. +func Shuffle[T any, Slice ~[]T](collection Slice) Slice { + mutable.Shuffle(collection) + return collection +} + +// Reverse reverses array so that the first element becomes the last, the second element becomes the second to last, and so on. +// Play: https://go.dev/play/p/iv2e9jslfBM +// +// Deprecated: use mutable.Reverse() instead. +func Reverse[T any, Slice ~[]T](collection Slice) Slice { + mutable.Reverse(collection) + return collection +} + +// Fill fills elements of array with `initial` value. +// Play: https://go.dev/play/p/VwR34GzqEub +func Fill[T Clonable[T], Slice ~[]T](collection Slice, initial T) Slice { + result := make(Slice, 0, len(collection)) + + for range collection { + result = append(result, initial.Clone()) + } + + return result +} + +// Repeat builds a slice with N copies of initial value. +// Play: https://go.dev/play/p/g3uHXbmc3b6 +func Repeat[T Clonable[T]](count int, initial T) []T { + result := make([]T, 0, count) + + for i := 0; i < count; i++ { + result = append(result, initial.Clone()) + } + + return result +} + +// RepeatBy builds a slice with values returned by N calls of callback. +// Play: https://go.dev/play/p/ozZLCtX_hNU +func RepeatBy[T any](count int, predicate func(index int) T) []T { + result := make([]T, 0, count) + + for i := 0; i < count; i++ { + result = append(result, predicate(i)) + } + + return result +} + +// KeyBy transforms a slice or an array of structs to a map based on a pivot callback. +// Play: https://go.dev/play/p/mdaClUAT-zZ +func KeyBy[K comparable, V any](collection []V, iteratee func(item V) K) map[K]V { + result := make(map[K]V, len(collection)) + + for i := range collection { + k := iteratee(collection[i]) + result[k] = collection[i] + } + + return result +} + +// Associate returns a map containing key-value pairs provided by transform function applied to elements of the given slice. +// If any of two pairs would have the same key the last one gets added to the map. +// The order of keys in returned map is not specified and is not guaranteed to be the same from the original array. +// Play: https://go.dev/play/p/WHa2CfMO3Lr +func Associate[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V { + result := make(map[K]V, len(collection)) + + for i := range collection { + k, v := transform(collection[i]) + result[k] = v + } + + return result +} + +// SliceToMap returns a map containing key-value pairs provided by transform function applied to elements of the given slice. +// If any of two pairs would have the same key the last one gets added to the map. +// The order of keys in returned map is not specified and is not guaranteed to be the same from the original array. +// Alias of Associate(). +// Play: https://go.dev/play/p/WHa2CfMO3Lr +func SliceToMap[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V { + return Associate(collection, transform) +} + +// FilterSliceToMap returns a map containing key-value pairs provided by transform function applied to elements of the given slice. +// If any of two pairs would have the same key the last one gets added to the map. +// The order of keys in returned map is not specified and is not guaranteed to be the same from the original array. +// The third return value of the transform function is a boolean that indicates whether the key-value pair should be included in the map. +func FilterSliceToMap[T any, K comparable, V any](collection []T, transform func(item T) (K, V, bool)) map[K]V { + result := make(map[K]V, len(collection)) + + for i := range collection { + k, v, ok := transform(collection[i]) + if ok { + result[k] = v + } + } + + return result +} + +// Keyify returns a map with each unique element of the slice as a key. +func Keyify[T comparable, Slice ~[]T](collection Slice) map[T]struct{} { + result := make(map[T]struct{}, len(collection)) + + for i := range collection { + result[collection[i]] = struct{}{} + } + + return result +} + +// Drop drops n elements from the beginning of a slice or array. +// Play: https://go.dev/play/p/JswS7vXRJP2 +func Drop[T any, Slice ~[]T](collection Slice, n int) Slice { + if len(collection) <= n { + return make(Slice, 0) + } + + result := make(Slice, 0, len(collection)-n) + + return append(result, collection[n:]...) +} + +// DropRight drops n elements from the end of a slice or array. +// Play: https://go.dev/play/p/GG0nXkSJJa3 +func DropRight[T any, Slice ~[]T](collection Slice, n int) Slice { + if len(collection) <= n { + return Slice{} + } + + result := make(Slice, 0, len(collection)-n) + return append(result, collection[:len(collection)-n]...) +} + +// DropWhile drops elements from the beginning of a slice or array while the predicate returns true. +// Play: https://go.dev/play/p/7gBPYw2IK16 +func DropWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { + i := 0 + for ; i < len(collection); i++ { + if !predicate(collection[i]) { + break + } + } + + result := make(Slice, 0, len(collection)-i) + return append(result, collection[i:]...) +} + +// DropRightWhile drops elements from the end of a slice or array while the predicate returns true. +// Play: https://go.dev/play/p/3-n71oEC0Hz +func DropRightWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { + i := len(collection) - 1 + for ; i >= 0; i-- { + if !predicate(collection[i]) { + break + } + } + + result := make(Slice, 0, i+1) + return append(result, collection[:i+1]...) +} + +// DropByIndex drops elements from a slice or array by the index. +// A negative index will drop elements from the end of the slice. +// Play: https://go.dev/play/p/bPIH4npZRxS +func DropByIndex[T any](collection []T, indexes ...int) []T { + initialSize := len(collection) + if initialSize == 0 { + return make([]T, 0) + } + + for i := range indexes { + if indexes[i] < 0 { + indexes[i] = initialSize + indexes[i] + } + } + + indexes = Uniq(indexes) + sort.Ints(indexes) + + result := make([]T, 0, initialSize) + result = append(result, collection...) + + for i := range indexes { + if indexes[i]-i < 0 || indexes[i]-i >= initialSize-i { + continue + } + + result = append(result[:indexes[i]-i], result[indexes[i]-i+1:]...) + } + + return result +} + +// Reject is the opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. +// Play: https://go.dev/play/p/YkLMODy1WEL +func Reject[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := Slice{} + + for i := range collection { + if !predicate(collection[i], i) { + result = append(result, collection[i]) + } + } + + return result +} + +// RejectMap is the opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. +// The callback function should return two values: +// - the result of the mapping operation and +// - whether the result element should be included or not. +func RejectMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { + result := []R{} + + for i := range collection { + if r, ok := callback(collection[i], i); !ok { + result = append(result, r) + } + } + + return result +} + +// FilterReject mixes Filter and Reject, this method returns two slices, one for the elements of collection that +// predicate returns truthy for and one for the elements that predicate does not return truthy for. +func FilterReject[T any, Slice ~[]T](collection Slice, predicate func(T, int) bool) (kept Slice, rejected Slice) { + kept = make(Slice, 0, len(collection)) + rejected = make(Slice, 0, len(collection)) + + for i := range collection { + if predicate(collection[i], i) { + kept = append(kept, collection[i]) + } else { + rejected = append(rejected, collection[i]) + } + } + + return kept, rejected +} + +// Count counts the number of elements in the collection that compare equal to value. +// Play: https://go.dev/play/p/Y3FlK54yveC +func Count[T comparable](collection []T, value T) (count int) { + for i := range collection { + if collection[i] == value { + count++ + } + } + + return count +} + +// CountBy counts the number of elements in the collection for which predicate is true. +// Play: https://go.dev/play/p/ByQbNYQQi4X +func CountBy[T any](collection []T, predicate func(item T) bool) (count int) { + for i := range collection { + if predicate(collection[i]) { + count++ + } + } + + return count +} + +// CountValues counts the number of each element in the collection. +// Play: https://go.dev/play/p/-p-PyLT4dfy +func CountValues[T comparable](collection []T) map[T]int { + result := make(map[T]int) + + for i := range collection { + result[collection[i]]++ + } + + return result +} + +// CountValuesBy counts the number of each element return from mapper function. +// Is equivalent to chaining lo.Map and lo.CountValues. +// Play: https://go.dev/play/p/2U0dG1SnOmS +func CountValuesBy[T any, U comparable](collection []T, mapper func(item T) U) map[U]int { + result := make(map[U]int) + + for i := range collection { + result[mapper(collection[i])]++ + } + + return result +} + +// Subset returns a copy of a slice from `offset` up to `length` elements. Like `slice[start:start+length]`, but does not panic on overflow. +// Play: https://go.dev/play/p/tOQu1GhFcog +func Subset[T any, Slice ~[]T](collection Slice, offset int, length uint) Slice { + size := len(collection) + + if offset < 0 { + offset = size + offset + if offset < 0 { + offset = 0 + } + } + + if offset > size { + return Slice{} + } + + if length > uint(size)-uint(offset) { + length = uint(size - offset) + } + + return collection[offset : offset+int(length)] +} + +// Slice returns a copy of a slice from `start` up to, but not including `end`. Like `slice[start:end]`, but does not panic on overflow. +// Play: https://go.dev/play/p/8XWYhfMMA1h +func Slice[T any, Slice ~[]T](collection Slice, start int, end int) Slice { + size := len(collection) + + if start >= end { + return Slice{} + } + + if start > size { + start = size + } + if start < 0 { + start = 0 + } + + if end > size { + end = size + } + if end < 0 { + end = 0 + } + + return collection[start:end] +} + +// Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new. +// Play: https://go.dev/play/p/XfPzmf9gql6 +func Replace[T comparable, Slice ~[]T](collection Slice, old T, new T, n int) Slice { + result := make(Slice, len(collection)) + copy(result, collection) + + for i := range result { + if result[i] == old && n != 0 { + result[i] = new + n-- + } + } + + return result +} + +// ReplaceAll returns a copy of the slice with all non-overlapping instances of old replaced by new. +// Play: https://go.dev/play/p/a9xZFUHfYcV +func ReplaceAll[T comparable, Slice ~[]T](collection Slice, old T, new T) Slice { + return Replace(collection, old, new, -1) +} + +// Compact returns a slice of all non-zero elements. +// Play: https://go.dev/play/p/tXiy-iK6PAc +func Compact[T comparable, Slice ~[]T](collection Slice) Slice { + var zero T + + result := make(Slice, 0, len(collection)) + + for i := range collection { + if collection[i] != zero { + result = append(result, collection[i]) + } + } + + return result +} + +// IsSorted checks if a slice is sorted. +// Play: https://go.dev/play/p/mc3qR-t4mcx +func IsSorted[T constraints.Ordered](collection []T) bool { + for i := 1; i < len(collection); i++ { + if collection[i-1] > collection[i] { + return false + } + } + + return true +} + +// IsSortedByKey checks if a slice is sorted by iteratee. +// Play: https://go.dev/play/p/wiG6XyBBu49 +func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(item T) K) bool { + size := len(collection) + + for i := 0; i < size-1; i++ { + if iteratee(collection[i]) > iteratee(collection[i+1]) { + return false + } + } + + return true +} + +// Splice inserts multiple elements at index i. A negative index counts back +// from the end of the slice. The helper is protected against overflow errors. +// Play: https://go.dev/play/p/G5_GhkeSUBA +func Splice[T any, Slice ~[]T](collection Slice, i int, elements ...T) Slice { + sizeCollection := len(collection) + sizeElements := len(elements) + output := make(Slice, 0, sizeCollection+sizeElements) // preallocate memory for the output slice + + if sizeElements == 0 { + return append(output, collection...) // simple copy + } else if i > sizeCollection { + // positive overflow + return append(append(output, collection...), elements...) + } else if i < -sizeCollection { + // negative overflow + return append(append(output, elements...), collection...) + } else if i < 0 { + // backward + i = sizeCollection + i + } + + return append(append(append(output, collection[:i]...), elements...), collection[i:]...) +} diff --git a/vendor/github.com/samber/lo/string.go b/vendor/github.com/samber/lo/string.go new file mode 100644 index 0000000000..923faa32b1 --- /dev/null +++ b/vendor/github.com/samber/lo/string.go @@ -0,0 +1,234 @@ +package lo + +import ( + "math" + "regexp" + "strings" + "unicode" + "unicode/utf8" + + "github.com/samber/lo/internal/rand" + + "golang.org/x/text/cases" + "golang.org/x/text/language" +) + +var ( + LowerCaseLettersCharset = []rune("abcdefghijklmnopqrstuvwxyz") + UpperCaseLettersCharset = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + LettersCharset = append(LowerCaseLettersCharset, UpperCaseLettersCharset...) + NumbersCharset = []rune("0123456789") + AlphanumericCharset = append(LettersCharset, NumbersCharset...) + SpecialCharset = []rune("!@#$%^&*()_+-=[]{}|;':\",./<>?") + AllCharset = append(AlphanumericCharset, SpecialCharset...) + + // bearer:disable go_lang_permissive_regex_validation + splitWordReg = regexp.MustCompile(`([a-z])([A-Z0-9])|([a-zA-Z])([0-9])|([0-9])([a-zA-Z])|([A-Z])([A-Z])([a-z])`) + // bearer:disable go_lang_permissive_regex_validation + splitNumberLetterReg = regexp.MustCompile(`([0-9])([a-zA-Z])`) + maximumCapacity = math.MaxInt>>1 + 1 +) + +// RandomString return a random string. +// Play: https://go.dev/play/p/rRseOQVVum4 +func RandomString(size int, charset []rune) string { + if size <= 0 { + panic("lo.RandomString: Size parameter must be greater than 0") + } + if len(charset) <= 0 { + panic("lo.RandomString: Charset parameter must not be empty") + } + + // see https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go + sb := strings.Builder{} + sb.Grow(size) + // Calculate the number of bits required to represent the charset, + // e.g., for 62 characters, it would need 6 bits (since 62 -> 64 = 2^6) + letterIdBits := int(math.Log2(float64(nearestPowerOfTwo(len(charset))))) + // Determine the corresponding bitmask, + // e.g., for 62 characters, the bitmask would be 111111. + var letterIdMask int64 = 1<= 0; { + // Regenerate the random number if all available bits have been used + if remain == 0 { + cache, remain = rand.Int64(), letterIdMax + } + // Select a character from the charset + if idx := int(cache & letterIdMask); idx < len(charset) { + sb.WriteRune(charset[idx]) + i-- + } + // Shift the bits to the right to prepare for the next character selection, + // e.g., for 62 characters, shift by 6 bits. + cache >>= letterIdBits + // Decrease the remaining number of uses for the current random number. + remain-- + } + return sb.String() +} + +// nearestPowerOfTwo returns the nearest power of two. +func nearestPowerOfTwo(cap int) int { + n := cap - 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + if n < 0 { + return 1 + } + if n >= maximumCapacity { + return maximumCapacity + } + return n + 1 +} + +// Substring return part of a string. +// Play: https://go.dev/play/p/TQlxQi82Lu1 +func Substring[T ~string](str T, offset int, length uint) T { + rs := []rune(str) + size := len(rs) + + if offset < 0 { + offset = size + offset + if offset < 0 { + offset = 0 + } + } + + if offset >= size { + return Empty[T]() + } + + if length > uint(size)-uint(offset) { + length = uint(size - offset) + } + + return T(strings.ReplaceAll(string(rs[offset:offset+int(length)]), "\x00", "")) +} + +// ChunkString returns an array of strings split into groups the length of size. If array can't be split evenly, +// the final chunk will be the remaining elements. +// Play: https://go.dev/play/p/__FLTuJVz54 +func ChunkString[T ~string](str T, size int) []T { + if size <= 0 { + panic("lo.ChunkString: Size parameter must be greater than 0") + } + + if len(str) == 0 { + return []T{""} + } + + if size >= len(str) { + return []T{str} + } + + var chunks = make([]T, 0, ((len(str)-1)/size)+1) + currentLen := 0 + currentStart := 0 + for i := range str { + if currentLen == size { + chunks = append(chunks, str[currentStart:i]) + currentLen = 0 + currentStart = i + } + currentLen++ + } + chunks = append(chunks, str[currentStart:]) + return chunks +} + +// RuneLength is an alias to utf8.RuneCountInString which returns the number of runes in string. +// Play: https://go.dev/play/p/tuhgW_lWY8l +func RuneLength(str string) int { + return utf8.RuneCountInString(str) +} + +// PascalCase converts string to pascal case. +func PascalCase(str string) string { + items := Words(str) + for i := range items { + items[i] = Capitalize(items[i]) + } + return strings.Join(items, "") +} + +// CamelCase converts string to camel case. +func CamelCase(str string) string { + items := Words(str) + for i, item := range items { + item = strings.ToLower(item) + if i > 0 { + item = Capitalize(item) + } + items[i] = item + } + return strings.Join(items, "") +} + +// KebabCase converts string to kebab case. +func KebabCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "-") +} + +// SnakeCase converts string to snake case. +func SnakeCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "_") +} + +// Words splits string into an array of its words. +func Words(str string) []string { + str = splitWordReg.ReplaceAllString(str, `$1$3$5$7 $2$4$6$8$9`) + // example: Int8Value => Int 8Value => Int 8 Value + str = splitNumberLetterReg.ReplaceAllString(str, "$1 $2") + var result strings.Builder + for _, r := range str { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + result.WriteRune(r) + } else { + result.WriteRune(' ') + } + } + return strings.Fields(result.String()) +} + +// Capitalize converts the first character of string to upper case and the remaining to lower case. +func Capitalize(str string) string { + return cases.Title(language.English).String(str) +} + +// Ellipsis trims and truncates a string to a specified length **in bytes** and appends an ellipsis +// if truncated. If the string contains non-ASCII characters (which may occupy multiple bytes in UTF-8), +// truncating by byte length may split a character in the middle, potentially resulting in garbled output. +func Ellipsis(str string, length int) string { + str = strings.TrimSpace(str) + + if len(str) > length { + if len(str) < 3 || length < 3 { + return "..." + } + return strings.TrimSpace(str[0:length-3]) + "..." + } + + return str +} + +// Elipse trims and truncates a string to a specified length and appends an ellipsis if truncated. +// +// Deprecated: Use Ellipsis instead. +func Elipse(str string, length int) string { + return Ellipsis(str, length) +} diff --git a/vendor/github.com/samber/lo/time.go b/vendor/github.com/samber/lo/time.go new file mode 100644 index 0000000000..e98e80f9e8 --- /dev/null +++ b/vendor/github.com/samber/lo/time.go @@ -0,0 +1,85 @@ +package lo + +import "time" + +// Duration returns the time taken to execute a function. +func Duration(cb func()) time.Duration { + return Duration0(cb) +} + +// Duration0 returns the time taken to execute a function. +func Duration0(cb func()) time.Duration { + start := time.Now() + cb() + return time.Since(start) +} + +// Duration1 returns the time taken to execute a function. +func Duration1[A any](cb func() A) (A, time.Duration) { + start := time.Now() + a := cb() + return a, time.Since(start) +} + +// Duration2 returns the time taken to execute a function. +func Duration2[A, B any](cb func() (A, B)) (A, B, time.Duration) { + start := time.Now() + a, b := cb() + return a, b, time.Since(start) +} + +// Duration3 returns the time taken to execute a function. +func Duration3[A, B, C any](cb func() (A, B, C)) (A, B, C, time.Duration) { + start := time.Now() + a, b, c := cb() + return a, b, c, time.Since(start) +} + +// Duration4 returns the time taken to execute a function. +func Duration4[A, B, C, D any](cb func() (A, B, C, D)) (A, B, C, D, time.Duration) { + start := time.Now() + a, b, c, d := cb() + return a, b, c, d, time.Since(start) +} + +// Duration5 returns the time taken to execute a function. +func Duration5[A, B, C, D, E any](cb func() (A, B, C, D, E)) (A, B, C, D, E, time.Duration) { + start := time.Now() + a, b, c, d, e := cb() + return a, b, c, d, e, time.Since(start) +} + +// Duration6 returns the time taken to execute a function. +func Duration6[A, B, C, D, E, F any](cb func() (A, B, C, D, E, F)) (A, B, C, D, E, F, time.Duration) { + start := time.Now() + a, b, c, d, e, f := cb() + return a, b, c, d, e, f, time.Since(start) +} + +// Duration7 returns the time taken to execute a function. +func Duration7[A, B, C, D, E, F, G any](cb func() (A, B, C, D, E, F, G)) (A, B, C, D, E, F, G, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g := cb() + return a, b, c, d, e, f, g, time.Since(start) +} + +// Duration8 returns the time taken to execute a function. +func Duration8[A, B, C, D, E, F, G, H any](cb func() (A, B, C, D, E, F, G, H)) (A, B, C, D, E, F, G, H, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h := cb() + return a, b, c, d, e, f, g, h, time.Since(start) +} + +// Duration9 returns the time taken to execute a function. +func Duration9[A, B, C, D, E, F, G, H, I any](cb func() (A, B, C, D, E, F, G, H, I)) (A, B, C, D, E, F, G, H, I, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i := cb() + return a, b, c, d, e, f, g, h, i, time.Since(start) +} + +// Duration10 returns the time taken to execute a function. +func Duration10[A, B, C, D, E, F, G, H, I, J any](cb func() (A, B, C, D, E, F, G, H, I, J)) (A, B, C, D, E, F, G, H, I, J, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i, j := cb() + return a, b, c, d, e, f, g, h, i, j, time.Since(start) +} diff --git a/vendor/github.com/samber/lo/tuples.go b/vendor/github.com/samber/lo/tuples.go new file mode 100644 index 0000000000..e355d0ca88 --- /dev/null +++ b/vendor/github.com/samber/lo/tuples.go @@ -0,0 +1,1149 @@ +package lo + +// T2 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T2[A, B any](a A, b B) Tuple2[A, B] { + return Tuple2[A, B]{A: a, B: b} +} + +// T3 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T3[A, B, C any](a A, b B, c C) Tuple3[A, B, C] { + return Tuple3[A, B, C]{A: a, B: b, C: c} +} + +// T4 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T4[A, B, C, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] { + return Tuple4[A, B, C, D]{A: a, B: b, C: c, D: d} +} + +// T5 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T5[A, B, C, D, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] { + return Tuple5[A, B, C, D, E]{A: a, B: b, C: c, D: d, E: e} +} + +// T6 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T6[A, B, C, D, E, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] { + return Tuple6[A, B, C, D, E, F]{A: a, B: b, C: c, D: d, E: e, F: f} +} + +// T7 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T7[A, B, C, D, E, F, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] { + return Tuple7[A, B, C, D, E, F, G]{A: a, B: b, C: c, D: d, E: e, F: f, G: g} +} + +// T8 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T8[A, B, C, D, E, F, G, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] { + return Tuple8[A, B, C, D, E, F, G, H]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h} +} + +// T9 creates a tuple from a list of values. +// Play: https://go.dev/play/p/IllL3ZO4BQm +func T9[A, B, C, D, E, F, G, H, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] { + return Tuple9[A, B, C, D, E, F, G, H, I]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i} +} + +// Unpack2 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack2[A, B any](tuple Tuple2[A, B]) (A, B) { + return tuple.A, tuple.B +} + +// Unpack3 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack3[A, B, C any](tuple Tuple3[A, B, C]) (A, B, C) { + return tuple.A, tuple.B, tuple.C +} + +// Unpack4 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack4[A, B, C, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) { + return tuple.A, tuple.B, tuple.C, tuple.D +} + +// Unpack5 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack5[A, B, C, D, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) { + return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E +} + +// Unpack6 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack6[A, B, C, D, E, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) { + return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F +} + +// Unpack7 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack7[A, B, C, D, E, F, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) { + return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G +} + +// Unpack8 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack8[A, B, C, D, E, F, G, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) { + return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H +} + +// Unpack9 returns values contained in tuple. +// Play: https://go.dev/play/p/xVP_k0kJ96W +func Unpack9[A, B, C, D, E, F, G, H, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) { + return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H, tuple.I +} + +// Zip2 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip2[A, B any](a []A, b []B) []Tuple2[A, B] { + size := Max([]int{len(a), len(b)}) + + result := make([]Tuple2[A, B], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + + result = append(result, Tuple2[A, B]{ + A: _a, + B: _b, + }) + } + + return result +} + +// Zip3 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip3[A, B, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { + size := Max([]int{len(a), len(b), len(c)}) + + result := make([]Tuple3[A, B, C], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + + result = append(result, Tuple3[A, B, C]{ + A: _a, + B: _b, + C: _c, + }) + } + + return result +} + +// Zip4 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip4[A, B, C, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, C, D] { + size := Max([]int{len(a), len(b), len(c), len(d)}) + + result := make([]Tuple4[A, B, C, D], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + + result = append(result, Tuple4[A, B, C, D]{ + A: _a, + B: _b, + C: _c, + D: _d, + }) + } + + return result +} + +// Zip5 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip5[A, B, C, D, E any](a []A, b []B, c []C, d []D, e []E) []Tuple5[A, B, C, D, E] { + size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) + + result := make([]Tuple5[A, B, C, D, E], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + + result = append(result, Tuple5[A, B, C, D, E]{ + A: _a, + B: _b, + C: _c, + D: _d, + E: _e, + }) + } + + return result +} + +// Zip6 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip6[A, B, C, D, E, F any](a []A, b []B, c []C, d []D, e []E, f []F) []Tuple6[A, B, C, D, E, F] { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Tuple6[A, B, C, D, E, F], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + + result = append(result, Tuple6[A, B, C, D, E, F]{ + A: _a, + B: _b, + C: _c, + D: _d, + E: _e, + F: _f, + }) + } + + return result +} + +// Zip7 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip7[A, B, C, D, E, F, G any](a []A, b []B, c []C, d []D, e []E, f []F, g []G) []Tuple7[A, B, C, D, E, F, G] { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) + + result := make([]Tuple7[A, B, C, D, E, F, G], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + + result = append(result, Tuple7[A, B, C, D, E, F, G]{ + A: _a, + B: _b, + C: _c, + D: _d, + E: _e, + F: _f, + G: _g, + }) + } + + return result +} + +// Zip8 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip8[A, B, C, D, E, F, G, H any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H) []Tuple8[A, B, C, D, E, F, G, H] { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h)}) + + result := make([]Tuple8[A, B, C, D, E, F, G, H], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + + result = append(result, Tuple8[A, B, C, D, E, F, G, H]{ + A: _a, + B: _b, + C: _c, + D: _d, + E: _e, + F: _f, + G: _g, + H: _h, + }) + } + + return result +} + +// Zip9 creates a slice of grouped elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +// Play: https://go.dev/play/p/jujaA6GaJTp +func Zip9[A, B, C, D, E, F, G, H, I any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I) []Tuple9[A, B, C, D, E, F, G, H, I] { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) + + result := make([]Tuple9[A, B, C, D, E, F, G, H, I], 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + _i, _ := Nth(i, index) + + result = append(result, Tuple9[A, B, C, D, E, F, G, H, I]{ + A: _a, + B: _b, + C: _c, + D: _d, + E: _e, + F: _f, + G: _g, + H: _h, + I: _i, + }) + } + + return result +} + +// ZipBy2 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy2[A any, B any, Out any](a []A, b []B, iteratee func(a A, b B) Out) []Out { + size := Max([]int{len(a), len(b)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + + result = append(result, iteratee(_a, _b)) + } + + return result +} + +// ZipBy3 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy3[A any, B any, C any, Out any](a []A, b []B, c []C, iteratee func(a A, b B, c C) Out) []Out { + size := Max([]int{len(a), len(b), len(c)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + + result = append(result, iteratee(_a, _b, _c)) + } + + return result +} + +// ZipBy4 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy4[A any, B any, C any, D any, Out any](a []A, b []B, c []C, d []D, iteratee func(a A, b B, c C, d D) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + + result = append(result, iteratee(_a, _b, _c, _d)) + } + + return result +} + +// ZipBy5 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy5[A any, B any, C any, D any, E any, Out any](a []A, b []B, c []C, d []D, e []E, iteratee func(a A, b B, c C, d D, e E) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e)) + } + + return result +} + +// ZipBy6 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy6[A any, B any, C any, D any, E any, F any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, iteratee func(a A, b B, c C, d D, e E, f F) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f)) + } + + return result +} + +// ZipBy7 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy7[A any, B any, C any, D any, E any, F any, G any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, iteratee func(a A, b B, c C, d D, e E, f F, g G) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g)) + } + + return result +} + +// ZipBy8 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy8[A any, B any, C any, D any, E any, F any, G any, H any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h)) + } + + return result +} + +// ZipBy9 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy9[A any, B any, C any, D any, E any, F any, G any, H any, I any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H, i I) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + _i, _ := Nth(i, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h, _i)) + } + + return result +} + +// Unzip2 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip2[A, B any](tuples []Tuple2[A, B]) ([]A, []B) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + } + + return r1, r2 +} + +// Unzip3 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip3[A, B, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + } + + return r1, r2, r3 +} + +// Unzip4 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip4[A, B, C, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, []C, []D) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + } + + return r1, r2, r3, r4 +} + +// Unzip5 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip5[A, B, C, D, E any](tuples []Tuple5[A, B, C, D, E]) ([]A, []B, []C, []D, []E) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + } + + return r1, r2, r3, r4, r5 +} + +// Unzip6 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip6[A, B, C, D, E, F any](tuples []Tuple6[A, B, C, D, E, F]) ([]A, []B, []C, []D, []E, []F) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + } + + return r1, r2, r3, r4, r5, r6 +} + +// Unzip7 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip7[A, B, C, D, E, F, G any](tuples []Tuple7[A, B, C, D, E, F, G]) ([]A, []B, []C, []D, []E, []F, []G) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + } + + return r1, r2, r3, r4, r5, r6, r7 +} + +// Unzip8 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip8[A, B, C, D, E, F, G, H any](tuples []Tuple8[A, B, C, D, E, F, G, H]) ([]A, []B, []C, []D, []E, []F, []G, []H) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) + } + + return r1, r2, r3, r4, r5, r6, r7, r8 +} + +// Unzip9 accepts an array of grouped elements and creates an array regrouping the elements +// to their pre-zip configuration. +// Play: https://go.dev/play/p/ciHugugvaAW +func Unzip9[A, B, C, D, E, F, G, H, I any](tuples []Tuple9[A, B, C, D, E, F, G, H, I]) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { + size := len(tuples) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + r9 := make([]I, 0, size) + + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) + r9 = append(r9, tuples[i].I) + } + + return r1, r2, r3, r4, r5, r6, r7, r8, r9 +} + +// UnzipBy2 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy2[In any, A any, B any](items []In, iteratee func(In) (a A, b B)) ([]A, []B) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + + for i := range items { + a, b := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + } + + return r1, r2 +} + +// UnzipBy3 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy3[In any, A any, B any, C any](items []In, iteratee func(In) (a A, b B, c C)) ([]A, []B, []C) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + + for i := range items { + a, b, c := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + } + + return r1, r2, r3 +} + +// UnzipBy4 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy4[In any, A any, B any, C any, D any](items []In, iteratee func(In) (a A, b B, c C, d D)) ([]A, []B, []C, []D) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + + for i := range items { + a, b, c, d := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + } + + return r1, r2, r3, r4 +} + +// UnzipBy5 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy5[In any, A any, B any, C any, D any, E any](items []In, iteratee func(In) (a A, b B, c C, d D, e E)) ([]A, []B, []C, []D, []E) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + + for i := range items { + a, b, c, d, e := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + } + + return r1, r2, r3, r4, r5 +} + +// UnzipBy6 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy6[In any, A any, B any, C any, D any, E any, F any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F)) ([]A, []B, []C, []D, []E, []F) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + + for i := range items { + a, b, c, d, e, f := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + } + + return r1, r2, r3, r4, r5, r6 +} + +// UnzipBy7 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy7[In any, A any, B any, C any, D any, E any, F any, G any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G)) ([]A, []B, []C, []D, []E, []F, []G) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + + for i := range items { + a, b, c, d, e, f, g := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + } + + return r1, r2, r3, r4, r5, r6, r7 +} + +// UnzipBy8 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy8[In any, A any, B any, C any, D any, E any, F any, G any, H any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H)) ([]A, []B, []C, []D, []E, []F, []G, []H) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + } + + return r1, r2, r3, r4, r5, r6, r7, r8 +} + +// UnzipBy9 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy9[In any, A any, B any, C any, D any, E any, F any, G any, H any, I any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H, i I)) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + r9 := make([]I, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h, i := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + r9 = append(r9, i) + } + + return r1, r2, r3, r4, r5, r6, r7, r8, r9 +} + +// CrossJoin2 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin2[A, B any](listA []A, listB []B) []Tuple2[A, B] { + return CrossJoinBy2(listA, listB, T2[A, B]) +} + +// CrossJoin3 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin3[A, B, C any](listA []A, listB []B, listC []C) []Tuple3[A, B, C] { + return CrossJoinBy3(listA, listB, listC, T3[A, B, C]) +} + +// CrossJoin4 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin4[A, B, C, D any](listA []A, listB []B, listC []C, listD []D) []Tuple4[A, B, C, D] { + return CrossJoinBy4(listA, listB, listC, listD, T4[A, B, C, D]) +} + +// CrossJoin5 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin5[A, B, C, D, E any](listA []A, listB []B, listC []C, listD []D, listE []E) []Tuple5[A, B, C, D, E] { + return CrossJoinBy5(listA, listB, listC, listD, listE, T5[A, B, C, D, E]) +} + +// CrossJoin6 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin6[A, B, C, D, E, F any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F) []Tuple6[A, B, C, D, E, F] { + return CrossJoinBy6(listA, listB, listC, listD, listE, listF, T6[A, B, C, D, E, F]) +} + +// CrossJoin7 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin7[A, B, C, D, E, F, G any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G) []Tuple7[A, B, C, D, E, F, G] { + return CrossJoinBy7(listA, listB, listC, listD, listE, listF, listG, T7[A, B, C, D, E, F, G]) +} + +// CrossJoin8 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin8[A, B, C, D, E, F, G, H any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, listH []H) []Tuple8[A, B, C, D, E, F, G, H] { + return CrossJoinBy8(listA, listB, listC, listD, listE, listF, listG, listH, T8[A, B, C, D, E, F, G, H]) +} + +// CrossJoin9 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. +// It returns an empty list if a list is empty. +func CrossJoin9[A, B, C, D, E, F, G, H, I any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, listH []H, listI []I) []Tuple9[A, B, C, D, E, F, G, H, I] { + return CrossJoinBy9(listA, listB, listC, listD, listE, listF, listG, listH, listI, T9[A, B, C, D, E, F, G, H, I]) +} + +// CrossJoinBy2 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy2[A, B, Out any](listA []A, listB []B, project func(a A, b B) Out) []Out { + size := len(listA) * len(listB) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + result = append(result, project(a, b)) + } + } + + return result +} + +// CrossJoinBy3 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy3[A, B, C, Out any](listA []A, listB []B, listC []C, project func(a A, b B, c C) Out) []Out { + size := len(listA) * len(listB) * len(listC) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + result = append(result, project(a, b, c)) + } + } + } + + return result +} + +// CrossJoinBy4 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy4[A, B, C, D, Out any](listA []A, listB []B, listC []C, listD []D, project func(a A, b B, c C, d D) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + result = append(result, project(a, b, c, d)) + } + } + } + } + + return result +} + +// CrossJoinBy5 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy5[A, B, C, D, E, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, project func(a A, b B, c C, d D, e E) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) * len(listE) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + for _, e := range listE { + result = append(result, project(a, b, c, d, e)) + } + } + } + } + } + + return result +} + +// CrossJoinBy6 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy6[A, B, C, D, E, F, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, project func(a A, b B, c C, d D, e E, f F) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) * len(listE) * len(listF) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + for _, e := range listE { + for _, f := range listF { + result = append(result, project(a, b, c, d, e, f)) + } + } + } + } + } + } + + return result +} + +// CrossJoinBy7 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy7[A, B, C, D, E, F, G, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, project func(a A, b B, c C, d D, e E, f F, g G) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) * len(listE) * len(listF) * len(listG) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + for _, e := range listE { + for _, f := range listF { + for _, g := range listG { + result = append(result, project(a, b, c, d, e, f, g)) + } + } + } + } + } + } + } + + return result +} + +// CrossJoinBy8 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy8[A, B, C, D, E, F, G, H, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, listH []H, project func(a A, b B, c C, d D, e E, f F, g G, h H) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) * len(listE) * len(listF) * len(listG) * len(listH) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + for _, e := range listE { + for _, f := range listF { + for _, g := range listG { + for _, h := range listH { + result = append(result, project(a, b, c, d, e, f, g, h)) + } + } + } + } + } + } + } + } + + return result +} + +// CrossJoinBy9 combines every items from one list with every items from others. +// It is the cartesian product of lists received as arguments. The project function +// is used to create the output values. +// It returns an empty list if a list is empty. +func CrossJoinBy9[A, B, C, D, E, F, G, H, I, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, listH []H, listI []I, project func(a A, b B, c C, d D, e E, f F, g G, h H, i I) Out) []Out { + size := len(listA) * len(listB) * len(listC) * len(listD) * len(listE) * len(listF) * len(listG) * len(listH) * len(listI) + if size == 0 { + return []Out{} + } + + result := make([]Out, 0, size) + + for _, a := range listA { + for _, b := range listB { + for _, c := range listC { + for _, d := range listD { + for _, e := range listE { + for _, f := range listF { + for _, g := range listG { + for _, h := range listH { + for _, i := range listI { + result = append(result, project(a, b, c, d, e, f, g, h, i)) + } + } + } + } + } + } + } + } + } + + return result +} diff --git a/vendor/github.com/samber/lo/type_manipulation.go b/vendor/github.com/samber/lo/type_manipulation.go new file mode 100644 index 0000000000..bcf990cd6d --- /dev/null +++ b/vendor/github.com/samber/lo/type_manipulation.go @@ -0,0 +1,189 @@ +package lo + +import "reflect" + +// IsNil checks if a value is nil or if it's a reference type with a nil underlying value. +func IsNil(x any) bool { + defer func() { recover() }() // nolint:errcheck + return x == nil || reflect.ValueOf(x).IsNil() +} + +// IsNotNil checks if a value is not nil or if it's not a reference type with a nil underlying value. +func IsNotNil(x any) bool { + return !IsNil(x) +} + +// ToPtr returns a pointer copy of value. +func ToPtr[T any](x T) *T { + return &x +} + +// Nil returns a nil pointer of type. +func Nil[T any]() *T { + return nil +} + +// EmptyableToPtr returns a pointer copy of value if it's nonzero. +// Otherwise, returns nil pointer. +func EmptyableToPtr[T any](x T) *T { + // 🤮 + isZero := reflect.ValueOf(&x).Elem().IsZero() + if isZero { + return nil + } + + return &x +} + +// FromPtr returns the pointer value or empty. +func FromPtr[T any](x *T) T { + if x == nil { + return Empty[T]() + } + + return *x +} + +// FromPtrOr returns the pointer value or the fallback value. +func FromPtrOr[T any](x *T, fallback T) T { + if x == nil { + return fallback + } + + return *x +} + +// ToSlicePtr returns a slice of pointer copy of value. +func ToSlicePtr[T any](collection []T) []*T { + result := make([]*T, len(collection)) + + for i := range collection { + result[i] = &collection[i] + } + return result +} + +// FromSlicePtr returns a slice with the pointer values. +// Returns a zero value in case of a nil pointer element. +func FromSlicePtr[T any](collection []*T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return Empty[T]() + } + return *x + }) +} + +// FromSlicePtrOr returns a slice with the pointer values or the fallback value. +// Play: https://go.dev/play/p/lbunFvzlUDX +func FromSlicePtrOr[T any](collection []*T, fallback T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return fallback + } + return *x + }) +} + +// ToAnySlice returns a slice with all elements mapped to `any` type +func ToAnySlice[T any](collection []T) []any { + result := make([]any, len(collection)) + for i := range collection { + result[i] = collection[i] + } + return result +} + +// FromAnySlice returns an `any` slice with all elements mapped to a type. +// Returns false in case of type conversion failure. +func FromAnySlice[T any](in []any) (out []T, ok bool) { + defer func() { + if r := recover(); r != nil { + out = []T{} + ok = false + } + }() + + result := make([]T, len(in)) + for i := range in { + result[i] = in[i].(T) + } + return result, true +} + +// Empty returns the zero value (https://go.dev/ref/spec#The_zero_value). +func Empty[T any]() T { + var zero T + return zero +} + +// IsEmpty returns true if argument is a zero value. +func IsEmpty[T comparable](v T) bool { + var zero T + return zero == v +} + +// IsNotEmpty returns true if argument is not a zero value. +func IsNotEmpty[T comparable](v T) bool { + var zero T + return zero != v +} + +// Coalesce returns the first non-empty arguments. Arguments must be comparable. +func Coalesce[T comparable](values ...T) (result T, ok bool) { + for i := range values { + if values[i] != result { + result = values[i] + ok = true + return + } + } + + return +} + +// CoalesceOrEmpty returns the first non-empty arguments. Arguments must be comparable. +func CoalesceOrEmpty[T comparable](v ...T) T { + result, _ := Coalesce(v...) + return result +} + +// CoalesceSlice returns the first non-zero slice. +func CoalesceSlice[T any](v ...[]T) ([]T, bool) { + for i := range v { + if v[i] != nil && len(v[i]) > 0 { + return v[i], true + } + } + return []T{}, false +} + +// CoalesceSliceOrEmpty returns the first non-zero slice. +func CoalesceSliceOrEmpty[T any](v ...[]T) []T { + for i := range v { + if v[i] != nil && len(v[i]) > 0 { + return v[i] + } + } + return []T{} +} + +// CoalesceMap returns the first non-zero map. +func CoalesceMap[K comparable, V any](v ...map[K]V) (map[K]V, bool) { + for i := range v { + if v[i] != nil && len(v[i]) > 0 { + return v[i], true + } + } + return map[K]V{}, false +} + +// CoalesceMapOrEmpty returns the first non-zero map. +func CoalesceMapOrEmpty[K comparable, V any](v ...map[K]V) map[K]V { + for i := range v { + if v[i] != nil && len(v[i]) > 0 { + return v[i] + } + } + return map[K]V{} +} diff --git a/vendor/github.com/samber/lo/types.go b/vendor/github.com/samber/lo/types.go new file mode 100644 index 0000000000..1c6f0d0057 --- /dev/null +++ b/vendor/github.com/samber/lo/types.go @@ -0,0 +1,123 @@ +package lo + +// Entry defines a key/value pairs. +type Entry[K comparable, V any] struct { + Key K + Value V +} + +// Tuple2 is a group of 2 elements (pair). +type Tuple2[A, B any] struct { + A A + B B +} + +// Unpack returns values contained in tuple. +func (t Tuple2[A, B]) Unpack() (A, B) { + return t.A, t.B +} + +// Tuple3 is a group of 3 elements. +type Tuple3[A, B, C any] struct { + A A + B B + C C +} + +// Unpack returns values contained in tuple. +func (t Tuple3[A, B, C]) Unpack() (A, B, C) { + return t.A, t.B, t.C +} + +// Tuple4 is a group of 4 elements. +type Tuple4[A, B, C, D any] struct { + A A + B B + C C + D D +} + +// Unpack returns values contained in tuple. +func (t Tuple4[A, B, C, D]) Unpack() (A, B, C, D) { + return t.A, t.B, t.C, t.D +} + +// Tuple5 is a group of 5 elements. +type Tuple5[A, B, C, D, E any] struct { + A A + B B + C C + D D + E E +} + +// Unpack returns values contained in tuple. +func (t Tuple5[A, B, C, D, E]) Unpack() (A, B, C, D, E) { + return t.A, t.B, t.C, t.D, t.E +} + +// Tuple6 is a group of 6 elements. +type Tuple6[A, B, C, D, E, F any] struct { + A A + B B + C C + D D + E E + F F +} + +// Unpack returns values contained in tuple. +func (t Tuple6[A, B, C, D, E, F]) Unpack() (A, B, C, D, E, F) { + return t.A, t.B, t.C, t.D, t.E, t.F +} + +// Tuple7 is a group of 7 elements. +type Tuple7[A, B, C, D, E, F, G any] struct { + A A + B B + C C + D D + E E + F F + G G +} + +// Unpack returns values contained in tuple. +func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) { + return t.A, t.B, t.C, t.D, t.E, t.F, t.G +} + +// Tuple8 is a group of 8 elements. +type Tuple8[A, B, C, D, E, F, G, H any] struct { + A A + B B + C C + D D + E E + F F + G G + H H +} + +// Unpack returns values contained in tuple. +func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) { + return t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H +} + +// Tuple9 is a group of 9 elements. +type Tuple9[A, B, C, D, E, F, G, H, I any] struct { + A A + B B + C C + D D + E E + F F + G G + H H + I I +} + +// Unpack returns values contained in tuple. +func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) { + return t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 68734e651d..6dfe0a3b7d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1553,6 +1553,13 @@ github.com/opencloud-eu/reva/v2/pkg/utils/cfg github.com/opencloud-eu/reva/v2/pkg/utils/ldap github.com/opencloud-eu/reva/v2/pkg/utils/list github.com/opencloud-eu/reva/v2/tests/cs3mocks/mocks +# github.com/opensearch-project/opensearch-go/v4 v4.5.0 +## explicit; go 1.22 +github.com/opensearch-project/opensearch-go/v4 +github.com/opensearch-project/opensearch-go/v4/internal/version +github.com/opensearch-project/opensearch-go/v4/opensearchapi +github.com/opensearch-project/opensearch-go/v4/opensearchtransport +github.com/opensearch-project/opensearch-go/v4/signer # github.com/opentracing/opentracing-go v1.2.0 ## explicit; go 1.14 github.com/opentracing/opentracing-go @@ -1678,6 +1685,12 @@ github.com/russellhaering/goxmldsig/types # github.com/russross/blackfriday/v2 v2.1.0 ## explicit github.com/russross/blackfriday/v2 +# github.com/samber/lo v1.51.0 +## explicit; go 1.18 +github.com/samber/lo +github.com/samber/lo/internal/constraints +github.com/samber/lo/internal/rand +github.com/samber/lo/mutable # github.com/segmentio/kafka-go v0.4.48 ## explicit; go 1.15 github.com/segmentio/kafka-go