diff --git a/.golangci.yml b/.golangci.yml index 7e261cdd..ece51689 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -31,7 +31,6 @@ linters-settings: package-average: 10 godox: keywords: - - NOTE - OPTIMIZE - HACK - TODO diff --git a/api/clientSyncRunner/runner_test.go b/api/clientSyncRunner/runner_test.go index 17596bb5..13179e0d 100644 --- a/api/clientSyncRunner/runner_test.go +++ b/api/clientSyncRunner/runner_test.go @@ -8,7 +8,6 @@ import ( clientsyncrunner "queryorchestration/api/clientSyncRunner" clientsync "queryorchestration/internal/client/sync" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/server/runner" "queryorchestration/internal/serviceconfig/queue/documentsync" @@ -63,10 +62,10 @@ func TestQueryRunner(t *testing.T) { docId := uuid.New() total := int64(1) - pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(database.MustToDBUUID(bod.ID), int32(100), int32(0)). + pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(bod.ID, int32(100), int32(0)). WillReturnRows( pgxmock.NewRows([]string{"id", "totalCount"}). - AddRow(database.MustToDBUUID(docId), &total), + AddRow(&docId, &total), ) mockSQS.EXPECT(). SendMessage( diff --git a/api/docCleanRunner/runner_test.go b/api/docCleanRunner/runner_test.go index eebfa82a..08ba0b6c 100644 --- a/api/docCleanRunner/runner_test.go +++ b/api/docCleanRunner/runner_test.go @@ -9,7 +9,6 @@ import ( "testing" doccleanrunner "queryorchestration/api/docCleanRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" documentclean "queryorchestration/internal/document/clean" @@ -76,7 +75,7 @@ func TestDocCleanRunner(t *testing.T) { Bucket: "bucket_name", Key: "/i/am/here", } - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID pool.ExpectQuery("name: HasDocumentCleanEntry :one").WithArgs(dbid).WillReturnRows( pgxmock.NewRows([]string{"isclean"}). @@ -85,7 +84,7 @@ func TestDocCleanRunner(t *testing.T) { pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(dbid). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(dbid, database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(dbid, doc.ClientID, doc.Hash), ) pool.ExpectQuery("name: GetDocumentEntry :one").WithArgs(dbid).WillReturnRows( pgxmock.NewRows([]string{"documentId", "bucket", "key"}). @@ -97,7 +96,7 @@ func TestDocCleanRunner(t *testing.T) { Cleanmimetype: repository.Cleanmimetype(mimeType), } pool.ExpectBegin() - cleanid := database.MustToDBUUID(uuid.New()) + cleanid := uuid.New() pool.ExpectQuery("name: GetMostRecentDocumentCleanEntry :one").WithArgs(dbid). WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}), diff --git a/api/docInitRunner/runner_test.go b/api/docInitRunner/runner_test.go index e1dce040..ce47d727 100644 --- a/api/docInitRunner/runner_test.go +++ b/api/docInitRunner/runner_test.go @@ -7,7 +7,6 @@ import ( "testing" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" documentinit "queryorchestration/internal/document/init" @@ -79,22 +78,22 @@ func TestDocInitRunner(t *testing.T) { Body: &body, } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(docinfo.Hash, database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(docinfo.Hash, clientId).WillReturnRows( pgxmock.NewRows([]string{"id"}), ) pool.ExpectBegin() - pool.ExpectQuery("name: CreateDocument :one").WithArgs(database.MustToDBUUID(clientId), docinfo.Hash). + pool.ExpectQuery("name: CreateDocument :one").WithArgs(clientId, docinfo.Hash). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(docinfo.ID)), + AddRow(docinfo.ID), ) - pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(database.MustToDBUUID(docinfo.ID), bucketName, location). + pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(docinfo.ID, bucketName, location). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(docinfo.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(docinfo.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(docinfo.ID), database.MustToDBUUID(docinfo.ClientID), "example"), + AddRow(docinfo.ID, docinfo.ClientID, "example"), ) mockSQS.EXPECT(). @@ -162,22 +161,22 @@ func TestProcessRecord(t *testing.T) { }, } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(docinfo.Hash, database.MustToDBUUID(j.ID)).WillReturnRows( + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(docinfo.Hash, j.ID).WillReturnRows( pgxmock.NewRows([]string{"id"}), ) pool.ExpectBegin() - pool.ExpectQuery("name: CreateDocument :one").WithArgs(database.MustToDBUUID(j.ID), docinfo.Hash). + pool.ExpectQuery("name: CreateDocument :one").WithArgs(j.ID, docinfo.Hash). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(docinfo.ID)), + AddRow(docinfo.ID), ) - pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(database.MustToDBUUID(docinfo.ID), bucketName, location). + pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(docinfo.ID, bucketName, location). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(docinfo.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(docinfo.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(docinfo.ID), database.MustToDBUUID(docinfo.ClientID), "example"), + AddRow(docinfo.ID, docinfo.ClientID, "example"), ) mockSQS.EXPECT(). diff --git a/api/docSyncRunner/runner_test.go b/api/docSyncRunner/runner_test.go index b8e30bfa..1b088a37 100644 --- a/api/docSyncRunner/runner_test.go +++ b/api/docSyncRunner/runner_test.go @@ -8,7 +8,6 @@ import ( docsyncrunner "queryorchestration/api/docSyncRunner" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" documentsync "queryorchestration/internal/document/sync" @@ -69,15 +68,15 @@ func TestDocInitRunner(t *testing.T) { Body: &body, } - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(docinfo.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(docinfo.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(docinfo.ID), database.MustToDBUUID(docinfo.ClientID), "example"), + AddRow(docinfo.ID, docinfo.ClientID, "example"), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(j.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(j.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(j.ID), "client_id", "client_name", true), + AddRow(j.ID, "client_id", "client_name", true), ) mockSQS.EXPECT(). diff --git a/api/docTextRunner/runner_test.go b/api/docTextRunner/runner_test.go index 25438ca1..b9a6728d 100644 --- a/api/docTextRunner/runner_test.go +++ b/api/docTextRunner/runner_test.go @@ -7,12 +7,12 @@ import ( "testing" doctextrunner "queryorchestration/api/docTextRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" documenttext "queryorchestration/internal/document/text" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/querysync" + "queryorchestration/internal/serviceconfig/textract" queuemock "queryorchestration/mocks/queue" "github.com/aws/aws-sdk-go-v2/service/sqs" @@ -28,6 +28,7 @@ import ( type DocTextConfig struct { serviceconfig.BaseConfig querysync.QuerySyncConfig + textract.TextractConfig } func TestDocCleanRunner(t *testing.T) { @@ -64,29 +65,37 @@ func TestDocCleanRunner(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(doc.ID)).WillReturnRows( + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(doc.ID).WillReturnRows( pgxmock.NewRows([]string{"isextracted"}). AddRow(false), ) - cleanId := database.MustToDBUUID(uuid.New()) + cleanId := uuid.New() mimeType := "application/pdf" dbmimetype := repository.NullCleanmimetype{ Valid: true, Cleanmimetype: repository.Cleanmimetype(mimeType), } - pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(database.MustToDBUUID(doc.ID)).WillReturnRows( + pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(doc.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(cleanId, database.MustToDBUUID(doc.ID), &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(cleanId, doc.ID, &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), ) pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(cleanId).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(cleanId, database.MustToDBUUID(doc.ID), &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(cleanId, doc.ID, &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), ) - pool.ExpectQuery("name: AddDocumentTextEntry :one").WithArgs(pgxmock.AnyArg(), inloc.Bucket, inloc.Key, cleanId). + textId := uuid.New() + pool.ExpectBegin() + pool.ExpectQuery("name: GetDocumentTextExtractionByHash :one").WithArgs(cleanId, "example").WillReturnRows( + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}), + ) + pool.ExpectQuery("name: AddDocumentText :one").WithArgs(inloc.Bucket, inloc.Key, cleanId, "example"). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(uuid.New())), + AddRow(textId), ) + pool.ExpectExec("name: AddDocumentTextEntry :exec").WithArgs(textId, pgxmock.AnyArg()). + WillReturnResult(pgxmock.NewResult("", 1)) + pool.ExpectCommit() mockSQS.EXPECT(). SendMessage( diff --git a/api/queryAPI/client_test.go b/api/queryAPI/client_test.go index e1c6d0c9..a462c117 100644 --- a/api/queryAPI/client_test.go +++ b/api/queryAPI/client_test.go @@ -10,7 +10,6 @@ import ( queryapi "queryorchestration/api/queryAPI" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -48,7 +47,7 @@ func TestCreateClient(t *testing.T) { pool.ExpectQuery("name: CreateClient :one").WithArgs(body.Id, body.Name).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(uuid.New())), + AddRow(uuid.New()), ) err = cons.CreateClient(ctx) @@ -81,7 +80,7 @@ func TestGetClient(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(clientUid), "client_id", "client_name", true), + AddRow(clientUid, "client_id", "client_name", true), ) err = cons.GetClient(ctx, id) @@ -132,14 +131,14 @@ func TestUpdateClient(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(intid), "clientid", "client_name", true), + AddRow(intid, "clientid", "client_name", true), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(intid)).WillReturnRows( + pool.ExpectQuery("name: GetClient :one").WithArgs(intid).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(intid), "clientid", "client_name", true), + AddRow(intid, "clientid", "client_name", true), ) pool.ExpectBegin() - pool.ExpectExec("name: AddClientCanSync :exec").WithArgs(*body.CanSync, database.MustToDBUUID(intid)). + pool.ExpectExec("name: AddClientCanSync :exec").WithArgs(*body.CanSync, intid). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() diff --git a/api/queryAPI/collector_test.go b/api/queryAPI/collector_test.go index 3084ba76..13c63f71 100644 --- a/api/queryAPI/collector_test.go +++ b/api/queryAPI/collector_test.go @@ -11,7 +11,6 @@ import ( queryapi "queryorchestration/api/queryAPI" "queryorchestration/internal/collector" collectorset "queryorchestration/internal/collector/set" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/clientsync" @@ -20,7 +19,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/google/uuid" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" "github.com/labstack/echo/v4" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/assert" @@ -79,28 +77,28 @@ func TestSetCollector(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(current.ClientID), id, "name", true), + AddRow(current.ClientID, id, "name", true), ) - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(current.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(current.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(current.ClientID), current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), + AddRow(current.ClientID, current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), ) - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]pgtype.UUID{database.MustToDBUUID((*body.Fields)[0].QueryId)}). + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{(*body.Fields)[0].QueryId}). WillReturnRows( pgxmock.NewRows([]string{"exist"}). AddRow(true), ) pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(5)), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(2)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(5), *body.MinimumCleanerVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, int32(5), *body.MinimumCleanerVersion). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(database.MustToDBUUID(current.ClientID), "a", database.MustToDBUUID((*body.Fields)[0].QueryId), int32(5)). + pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(current.ClientID, "a", (*body.Fields)[0].QueryId, int32(5)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -148,7 +146,7 @@ func TestGetCollectorByclientId(t *testing.T) { pool.ExpectQuery("name: GetCollectorByClientExternalID :one").WithArgs(id). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(coll.ClientID), coll.MinCleanVersion, coll.MinTextVersion, int32(1), int32(2), []byte("")), + AddRow(coll.ClientID, coll.MinCleanVersion, coll.MinTextVersion, int32(1), int32(2), []byte("")), ) err = cons.GetCollectorByClientId(ctx, id) diff --git a/api/queryAPI/documents_test.go b/api/queryAPI/documents_test.go index 04c4871d..6081d85d 100644 --- a/api/queryAPI/documents_test.go +++ b/api/queryAPI/documents_test.go @@ -8,7 +8,6 @@ import ( "testing" queryapi "queryorchestration/api/queryAPI" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" @@ -57,7 +56,7 @@ func TestListDocumentsByClientId(t *testing.T) { pool.ExpectQuery("name: ListDocumentsByClientExternalId :many").WithArgs(clientId). WillReturnRows( pgxmock.NewRows([]string{"id", "hash"}). - AddRow(database.MustToDBUUID(doc[0].Id), "hash"), + AddRow(doc[0].Id, "hash"), ) err = cons.ListDocumentsByClientId(ctx, clientId) @@ -104,10 +103,10 @@ func TestGetDocument(t *testing.T) { }, } - pool.ExpectQuery("name: GetDocumentExternal :one").WithArgs(database.MustToDBUUID(docId)). + pool.ExpectQuery("name: GetDocumentExternal :one").WithArgs(&docId). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash", "fields"}). - AddRow(database.MustToDBUUID(doc.Id), "externalID", "example", []byte(`{"json": "hello"}`)), + AddRow(doc.Id, "externalID", "example", []byte(`{"json": "hello"}`)), ) err = cons.GetDocument(ctx, docId) diff --git a/api/queryAPI/query_test.go b/api/queryAPI/query_test.go index 93814d07..72bf0873 100644 --- a/api/queryAPI/query_test.go +++ b/api/queryAPI/query_test.go @@ -10,7 +10,6 @@ import ( queryapi "queryorchestration/api/queryAPI" "queryorchestration/internal/collector" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/query" @@ -26,7 +25,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/google/uuid" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" "github.com/labstack/echo/v4" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/assert" @@ -61,13 +59,13 @@ func TestCreateQuery(t *testing.T) { pool.ExpectBeginTx(pgx.TxOptions{}) pool.ExpectQuery("name: CreateQuery :one").WithArgs(repository.QuerytypeContextFull).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(id)), + AddRow(id), ) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(id), int32(1)). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(id, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -97,7 +95,7 @@ func TestListQueries(t *testing.T) { pool.ExpectQuery("name: ListQueries :many").WithArgs().WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(id), repository.QuerytypeContextFull, int32(1), int32(2), []byte(""), []pgtype.UUID{}), + AddRow(id, repository.QuerytypeContextFull, int32(1), int32(2), []byte(""), []uuid.UUID{}), ) err = cons.ListQueries(ctx) @@ -138,9 +136,9 @@ func TestGetQuery(t *testing.T) { ctx.Set("id", id) - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(id), repository.QuerytypeContextFull, int32(1), int32(2), nil, []pgtype.UUID{}), + AddRow(id, repository.QuerytypeContextFull, int32(1), int32(2), nil, []uuid.UUID{}), ) err = cons.GetQuery(ctx, id) @@ -194,13 +192,13 @@ func TestUpdateQuery(t *testing.T) { ctx.Set("id", id) - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(id), repository.QuerytypeContextFull, int32(1), int32(2), []byte(""), []pgtype.UUID{}), + AddRow(id, repository.QuerytypeContextFull, int32(1), int32(2), []byte(""), []uuid.UUID{}), ) pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(id), av). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(id, av). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() mockSQS.EXPECT(). @@ -262,18 +260,18 @@ func TestTestQuery(t *testing.T) { rec := httptest.NewRecorder() ctx := e.NewContext(req, rec) - reqID := database.MustToDBUUID(uuid.New()) - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(params.QueryID), ¶ms.QueryVersion).WillReturnRows( + reqID := uuid.New() + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(¶ms.QueryID, ¶ms.QueryVersion).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(params.QueryID), repository.QuerytypeJsonExtractor, int32(1), params.QueryVersion+1, []byte("{\"path\":\"oldkey\"}"), []pgtype.UUID{reqID}), + AddRow(params.QueryID, repository.QuerytypeJsonExtractor, int32(1), params.QueryVersion+1, []byte("{\"path\":\"oldkey\"}"), []uuid.UUID{reqID}), ) strVal := "{\"mykey\":\"example_value\",\"oldkey\":\"old_value\"}" - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(params.QueryID), ¶ms.QueryVersion, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(¶ms.QueryID, ¶ms.QueryVersion, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(uuid.New()), reqID, repository.QuerytypeContextFull, &strVal), + AddRow(&uuid.UUID{}, reqID, repository.QuerytypeContextFull, &strVal), ) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(params.QueryID)).WillReturnRows( + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(params.QueryID).WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte("{\"path\":\"oldkey\"}")), ) diff --git a/api/queryAPI/status_test.go b/api/queryAPI/status_test.go index bc2eade8..97c9f360 100644 --- a/api/queryAPI/status_test.go +++ b/api/queryAPI/status_test.go @@ -9,7 +9,6 @@ import ( queryapi "queryorchestration/api/queryAPI" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -41,9 +40,9 @@ func TestGetClientStatus(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(clientId), id, "name", true), + AddRow(clientId, id, "name", true), ) - pool.ExpectQuery("name: IsClientSynced :one").WithArgs(database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: IsClientSynced :one").WithArgs(&clientId).WillReturnRows( pgxmock.NewRows([]string{"issynced"}). AddRow(true), ) diff --git a/api/queryRunner/runner_test.go b/api/queryRunner/runner_test.go index d014ce77..44f9e830 100644 --- a/api/queryRunner/runner_test.go +++ b/api/queryRunner/runner_test.go @@ -7,7 +7,6 @@ import ( "testing" queryrunner "queryorchestration/api/queryRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" "queryorchestration/internal/query/result" @@ -71,10 +70,11 @@ func TestQueryRunner(t *testing.T) { } qcfg := "{\"path\":\"examplekey\"}" + reqQuery := uuid.New() query := &resultprocessor.Query{ ID: doc.QueryID, Version: 2, - RequiredQueryIDs: &[]uuid.UUID{uuid.New()}, + RequiredQueryIDs: &[]uuid.UUID{reqQuery}, Config: &qcfg, } params := &resultset.Set{ @@ -83,49 +83,49 @@ func TestQueryRunner(t *testing.T) { cleanEntryId := uuid.New() textEntryId := uuid.New() - pool.ExpectQuery("name: GetTextEntryByDocId :one").WithArgs(database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: GetTextEntryByDocId :one").WithArgs(params.DocumentID). WillReturnRows( - pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "cleanEntryId"}). - AddRow(database.MustToDBUUID(textEntryId), database.MustToDBUUID(params.DocumentID), "buket", "/i/am/here", int32(1), database.MustToDBUUID(cleanEntryId)), + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}). + AddRow(textEntryId, params.DocumentID, "buket", "/i/am/here", int32(1), "example", cleanEntryId), ) - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), database.MustToDBUUIDArray(*query.RequiredQueryIDs)), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), *query.RequiredQueryIDs), ) - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(query.ID), &query.Version).WillReturnRows( + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(&query.ID, &query.Version).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), database.MustToDBUUIDArray(*query.RequiredQueryIDs)), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), *query.RequiredQueryIDs), ) requiredResultId := uuid.New() strVal := "{\"examplekey\":\"example_value\"}" - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(requiredResultId), database.MustToDBUUID((*query.RequiredQueryIDs)[0]), repository.QuerytypeContextFull, &strVal), + AddRow(&requiredResultId, (*query.RequiredQueryIDs)[0], repository.QuerytypeContextFull, &strVal), ) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(qcfg)), ) pool.ExpectBegin() resultId := uuid.New() - pool.ExpectQuery("name: AddResult :one").WithArgs(database.MustToDBUUID(query.ID), pgxmock.AnyArg(), database.MustToDBUUID(textEntryId), query.Version). + pool.ExpectQuery("name: AddResult :one").WithArgs(query.ID, pgxmock.AnyArg(), textEntryId, query.Version). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(resultId)), + AddRow(resultId), ) - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(requiredResultId), database.MustToDBUUID((*query.RequiredQueryIDs)[0]), repository.QuerytypeContextFull, &strVal), + AddRow(&requiredResultId, (*query.RequiredQueryIDs)[0], repository.QuerytypeContextFull, &strVal), ) - pool.ExpectExec("name: AddResultDependency :exec").WithArgs(database.MustToDBUUID(resultId), database.MustToDBUUID(requiredResultId)). + pool.ExpectExec("name: AddResultDependency :exec").WithArgs(resultId, requiredResultId). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(database.MustToDBUUID(query.ID), database.MustToDBUUID(doc.DocumentID)). + pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(query.ID, doc.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"queryId"}). - AddRow(database.MustToDBUUID((*query.RequiredQueryIDs)[0])), + AddRow(&reqQuery), ) mockSQS.EXPECT(). diff --git a/api/querySyncRunner/runner_test.go b/api/querySyncRunner/runner_test.go index b8f2324b..f2dc4482 100644 --- a/api/querySyncRunner/runner_test.go +++ b/api/querySyncRunner/runner_test.go @@ -7,7 +7,6 @@ import ( "testing" querysyncrunner "queryorchestration/api/querySyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultsync "queryorchestration/internal/query/result/sync" querysync "queryorchestration/internal/query/sync" @@ -63,19 +62,20 @@ func TestQueryRunner(t *testing.T) { Body: &body, } + reqId := uuid.New() qs := []uuid.UUID{ - uuid.New(), + reqId, } - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(doc.ID). WillReturnRows( pgxmock.NewRows([]string{"isextracted"}). AddRow(true), ) - pool.ExpectQuery("name: ListUnsyncedNoDepsQueriesByDocId :many").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: ListUnsyncedNoDepsQueriesByDocId :many").WithArgs(&doc.ID). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(qs[0])), + AddRow(&reqId), ) mockSQS.EXPECT(). diff --git a/api/queryVersionSyncRunner/runner_test.go b/api/queryVersionSyncRunner/runner_test.go index 24b2949a..0e368181 100644 --- a/api/queryVersionSyncRunner/runner_test.go +++ b/api/queryVersionSyncRunner/runner_test.go @@ -7,7 +7,6 @@ import ( "testing" queryversionsyncrunner "queryorchestration/api/queryVersionSyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" queryversionsync "queryorchestration/internal/query/versionsync" "queryorchestration/internal/server/runner" @@ -60,16 +59,18 @@ func TestQueryRunner(t *testing.T) { Body: &body, } + clientOne := uuid.New() + clientTwo := uuid.New() clientIds := []uuid.UUID{ - uuid.New(), - uuid.New(), + clientOne, + clientTwo, } - pool.ExpectQuery("name: ListQueryClientIDs :many").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: ListQueryClientIDs :many").WithArgs(&doc.ID). WillReturnRows( pgxmock.NewRows([]string{"clientId"}). - AddRow(database.MustToDBUUID(clientIds[0])). - AddRow(database.MustToDBUUID(clientIds[1])), + AddRow(clientOne). + AddRow(clientTwo), ) mockSQS.EXPECT(). diff --git a/build/Dockerfile b/build/Dockerfile index c7ce6c2d..95f3980c 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -25,8 +25,6 @@ ENV PWD=/app WORKDIR ${PWD} -COPY database/migrations/ database/migrations/ - COPY --from=build /bin/ . EXPOSE 8080 diff --git a/cmd/docTextRunner/main.go b/cmd/docTextRunner/main.go index 611b0b31..ffa02128 100644 --- a/cmd/docTextRunner/main.go +++ b/cmd/docTextRunner/main.go @@ -16,6 +16,7 @@ import ( documenttext "queryorchestration/internal/document/text" "queryorchestration/internal/server/runner" "queryorchestration/internal/serviceconfig/queue/querysync" + "queryorchestration/internal/serviceconfig/textract" _ "github.com/lib/pq" ) @@ -23,6 +24,7 @@ import ( type DocTextConfig struct { runner.BaseConfig querysync.QuerySyncConfig + textract.TextractConfig } func main() { diff --git a/database/queries/text.sql b/database/queries/text.sql deleted file mode 100644 index cfa7a355..00000000 --- a/database/queries/text.sql +++ /dev/null @@ -1,12 +0,0 @@ --- name: IsDocumentTextExtracted :one -SELECT EXISTS( - SELECT 1 FROM currentTextEntries WHERE documentId = @documentId -); - --- name: AddDocumentTextEntry :one -INSERT INTO documentTextExtractions (version, bucket, key, cleanEntryId) VALUES ($1, $2, $3, $4) returning id; - --- name: GetTextEntryByDocId :one -SELECT id, documentId, bucket, key, version, cleanEntryId - FROM currentTextEntries - WHERE documentId = @documentId; diff --git a/go.mod b/go.mod index 964390c6..9d9d5d86 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/aws/aws-sdk-go-v2/config v1.29.9 github.com/aws/aws-sdk-go-v2/service/s3 v1.78.1 github.com/aws/aws-sdk-go-v2/service/sqs v1.38.1 + github.com/aws/aws-sdk-go-v2/service/textract v1.35.1 github.com/caarlos0/env/v11 v11.3.1 github.com/getkin/kin-openapi v0.129.0 github.com/go-playground/validator/v10 v10.25.0 diff --git a/go.sum b/go.sum index 149f45d4..ccf7ad77 100644 --- a/go.sum +++ b/go.sum @@ -47,6 +47,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.1 h1:KwuLovgQPcdjNMfFt9OhUd9a github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.1/go.mod h1:MlYRNmYu/fGPoxBQVvBYr9nyr948aY/WLUvwBMBJubs= github.com/aws/aws-sdk-go-v2/service/sts v1.33.17 h1:PZV5W8yk4OtH1JAuhV2PXwwO9v5G5Aoj+eMCn4T+1Kc= github.com/aws/aws-sdk-go-v2/service/sts v1.33.17/go.mod h1:cQnB8CUnxbMU82JvlqjKR2HBOm3fe9pWorWBza6MBJ4= +github.com/aws/aws-sdk-go-v2/service/textract v1.35.1 h1:tsGagA+4oEfrGVGfkcVhtQ5vq1YFwFdmDRfLsqm+0vE= +github.com/aws/aws-sdk-go-v2/service/textract v1.35.1/go.mod h1:vj7T9jmJFer1JiUKWWCBcNPdNXqzNAeWUxh/s2/Up5Y= github.com/aws/smithy-go v1.22.3 h1:Z//5NuZCSW6R4PhQ93hShNbyBbn8BWCmCVCt+Q8Io5k= github.com/aws/smithy-go v1.22.3/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= diff --git a/internal/client/create.go b/internal/client/create.go index 26ceb2eb..72abe157 100644 --- a/internal/client/create.go +++ b/internal/client/create.go @@ -6,7 +6,6 @@ import ( "regexp" "strings" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "github.com/google/uuid" @@ -31,7 +30,7 @@ func (s *Service) Create(ctx context.Context, params CreateParams) (uuid.UUID, e return uuid.Nil, err } - return database.MustToUUID(id), nil + return id, nil } func (s *Service) normalizeCreate(params *CreateParams) error { diff --git a/internal/client/create_test.go b/internal/client/create_test.go index 55ae7de2..ccb52778 100644 --- a/internal/client/create_test.go +++ b/internal/client/create_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -34,7 +33,7 @@ func TestCreate(t *testing.T) { pool.ExpectQuery("name: CreateClient :one").WithArgs(params.ExternalId, params.Name). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(aid)), + AddRow(aid), ) id, err := svc.Create(ctx, params) diff --git a/internal/client/get.go b/internal/client/get.go index edbe93a8..65d88e3d 100644 --- a/internal/client/get.go +++ b/internal/client/get.go @@ -3,14 +3,13 @@ package client import ( "context" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "github.com/google/uuid" ) func (s *Service) Get(ctx context.Context, id uuid.UUID) (*Client, error) { - client, err := s.cfg.GetDBQueries().GetClient(ctx, database.MustToDBUUID(id)) + client, err := s.cfg.GetDBQueries().GetClient(ctx, id) if err != nil { return nil, err } @@ -29,7 +28,7 @@ func (s *Service) GetByExternalId(ctx context.Context, id string) (*Client, erro func parseFullClient(client *repository.Fullclient) *Client { return &Client{ - ID: database.MustToUUID(client.ID), + ID: client.ID, ExternalID: client.Externalid, Name: client.Name, CanSync: client.Cansync, diff --git a/internal/client/get_test.go b/internal/client/get_test.go index e9067845..08364e07 100644 --- a/internal/client/get_test.go +++ b/internal/client/get_test.go @@ -5,7 +5,6 @@ import ( "errors" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -28,10 +27,10 @@ func TestGet(t *testing.T) { id := uuid.New() - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: GetClient :one").WithArgs(id). WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(id), "client_id", "client_name", false), + AddRow(id, "client_id", "client_name", false), ) cli, err := svc.Get(ctx, id) @@ -44,7 +43,7 @@ func TestGet(t *testing.T) { }, cli) dberr := "database failure" - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: GetClient :one").WithArgs(id). WillReturnError(errors.New(dberr)) _, err = svc.Get(ctx, id) @@ -68,7 +67,7 @@ func TestGetByExternalId(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId). WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(id), "client_id", "client_name", false), + AddRow(id, "client_id", "client_name", false), ) cli, err := svc.GetByExternalId(ctx, externalId) @@ -81,7 +80,7 @@ func TestGetByExternalId(t *testing.T) { }, cli) dberr := "database failure" - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: GetClient :one").WithArgs(id). WillReturnError(errors.New(dberr)) _, err = svc.Get(ctx, id) @@ -90,14 +89,14 @@ func TestGetByExternalId(t *testing.T) { func TestParseFullClient(t *testing.T) { in := &repository.Fullclient{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Externalid: "external_id", Name: "name", Cansync: true, } out := parseFullClient(in) assert.EqualExportedValues(t, &Client{ - ID: database.MustToUUID(in.ID), + ID: in.ID, ExternalID: "external_id", Name: "name", CanSync: true, diff --git a/internal/client/status.go b/internal/client/status.go index 88b1cb1a..50400124 100644 --- a/internal/client/status.go +++ b/internal/client/status.go @@ -20,7 +20,7 @@ func (s *Service) GetStatusByExternalId(ctx context.Context, id string) (Status, return NOT_SYNCING, nil } - issynced, err := s.cfg.GetDBQueries().IsClientSynced(ctx, client.ID) + issynced, err := s.cfg.GetDBQueries().IsClientSynced(ctx, &client.ID) if err != nil { return NOT_SYNCING, err } else if issynced { diff --git a/internal/client/status_test.go b/internal/client/status_test.go index 0a2f0a11..b0aa84ec 100644 --- a/internal/client/status_test.go +++ b/internal/client/status_test.go @@ -6,7 +6,6 @@ import ( "testing" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -33,9 +32,9 @@ func TestGetStatusByExternalId(t *testing.T) { t.Run("is synced", func(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(clientId), externalId, "name", true), + AddRow(clientId, externalId, "name", true), ) - pool.ExpectQuery("name: IsClientSynced :one").WithArgs(database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: IsClientSynced :one").WithArgs(&clientId).WillReturnRows( pgxmock.NewRows([]string{"issynced"}). AddRow(true), ) @@ -47,9 +46,9 @@ func TestGetStatusByExternalId(t *testing.T) { t.Run("not synced", func(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(clientId), externalId, "name", true), + AddRow(clientId, externalId, "name", true), ) - pool.ExpectQuery("name: IsClientSynced :one").WithArgs(database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: IsClientSynced :one").WithArgs(&clientId).WillReturnRows( pgxmock.NewRows([]string{"issynced"}). AddRow(false), ) @@ -61,7 +60,7 @@ func TestGetStatusByExternalId(t *testing.T) { t.Run("not syncing", func(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(clientId), "id", "name", false), + AddRow(clientId, "id", "name", false), ) issynced, err := svc.GetStatusByExternalId(ctx, externalId) diff --git a/internal/client/sync/sync.go b/internal/client/sync/sync.go index 448f9c0e..d99499a7 100644 --- a/internal/client/sync/sync.go +++ b/internal/client/sync/sync.go @@ -7,7 +7,6 @@ import ( "log/slog" docsyncrunner "queryorchestration/api/docSyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig/queue" @@ -17,7 +16,7 @@ import ( func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { hasMore := true offset := int32(0) - dbid := database.MustToDBUUID(id) + dbid := id for hasMore { ids, err := s.cfg.GetDBQueries().ListDocumentIDsBatch(ctx, &repository.ListDocumentIDsBatchParams{ @@ -37,7 +36,7 @@ func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { err := s.cfg.SendToQueue(ctx, &queue.SendParams{ QueueURL: s.cfg.GetDocumentSyncURL(), Body: docsyncrunner.Body{ - ID: database.MustToUUID(id.ID), + ID: *id.ID, }, }) if err != nil { diff --git a/internal/client/sync/sync_test.go b/internal/client/sync/sync_test.go index 13c05a8e..74a7a764 100644 --- a/internal/client/sync/sync_test.go +++ b/internal/client/sync/sync_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" @@ -54,10 +53,10 @@ func TestTrigger(t *testing.T) { svc.batchSize = 1 total := int64(2) - pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(database.MustToDBUUID(clientId), svc.batchSize, int32(0)). + pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(clientId, svc.batchSize, int32(0)). WillReturnRows( pgxmock.NewRows([]string{"id", "totalCount"}). - AddRow(database.MustToDBUUID(docs[0].ID), &total), + AddRow(&docs[0].ID, &total), ) mockSQS.EXPECT(). SendMessage( @@ -68,10 +67,10 @@ func TestTrigger(t *testing.T) { mock.Anything, ). Return(&sqs.SendMessageOutput{}, nil) - pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(database.MustToDBUUID(clientId), svc.batchSize, int32(1)). + pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(clientId, svc.batchSize, int32(1)). WillReturnRows( pgxmock.NewRows([]string{"id", "totalCount"}). - AddRow(database.MustToDBUUID(docs[1].ID), &total), + AddRow(&docs[1].ID, &total), ) mockSQS.EXPECT(). SendMessage( @@ -104,7 +103,7 @@ func TestTrigger(t *testing.T) { clientId := uuid.New() svc.batchSize = 1 - pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(database.MustToDBUUID(clientId), svc.batchSize, int32(0)). + pool.ExpectQuery("name: ListDocumentIDsBatch :many").WithArgs(clientId, svc.batchSize, int32(0)). WillReturnRows( pgxmock.NewRows([]string{"id", "totalCount"}), ) diff --git a/internal/client/update.go b/internal/client/update.go index c100cbf3..e4141fd7 100644 --- a/internal/client/update.go +++ b/internal/client/update.go @@ -5,7 +5,6 @@ import ( "errors" "log/slog" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/validation" @@ -18,7 +17,7 @@ func (s *Service) UpdateByExternalId(ctx context.Context, id string, entity *Upd return err } - err = s.Update(ctx, database.MustToUUID(client.ID), entity) + err = s.Update(ctx, client.ID, entity) if err != nil { return err } @@ -52,7 +51,7 @@ func (s *Service) Update(ctx context.Context, id uuid.UUID, entity *Update) erro func (s *Service) submitUpdate(ctx context.Context, id uuid.UUID, entity *Update) error { return s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { - id := database.MustToDBUUID(id) + id := id if entity.Name != nil { err := q.UpdateClient(ctx, &repository.UpdateClientParams{ diff --git a/internal/client/update_test.go b/internal/client/update_test.go index c134037b..f4730cba 100644 --- a/internal/client/update_test.go +++ b/internal/client/update_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -32,10 +31,10 @@ func TestUpdate(t *testing.T) { } update := Update{} - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.Name, c.CanSync), + AddRow(c.ID, c.Name, c.CanSync), ) err = svc.Update(ctx, c.ID, &update) @@ -44,10 +43,10 @@ func TestUpdate(t *testing.T) { c.CanSync = false update.CanSync = &c.CanSync - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.Name, c.CanSync), + AddRow(c.ID, c.Name, c.CanSync), ) err = svc.Update(ctx, c.ID, &update) @@ -56,12 +55,12 @@ func TestUpdate(t *testing.T) { c.Name = "updated_name" update.Name = &c.Name - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.Name, c.CanSync), + AddRow(c.ID, c.Name, c.CanSync), ) - pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, database.MustToDBUUID(c.ID)). + pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, c.ID). WillReturnResult(pgxmock.NewResult("", 1)) err = svc.Update(ctx, c.ID, &update) @@ -134,7 +133,7 @@ func TestSubmitUpdate(t *testing.T) { update.CanSync = &c.CanSync pool.ExpectBegin() - pool.ExpectExec("name: AddClientCanSync :exec").WithArgs(*update.CanSync, database.MustToDBUUID(c.ID)). + pool.ExpectExec("name: AddClientCanSync :exec").WithArgs(*update.CanSync, c.ID). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -146,7 +145,7 @@ func TestSubmitUpdate(t *testing.T) { update.CanSync = nil pool.ExpectBegin() - pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, database.MustToDBUUID(c.ID)). + pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, c.ID). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -177,13 +176,13 @@ func TestUpdateByExternalId(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(c.ExternalID). WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.ExternalID, c.Name, c.CanSync), + AddRow(c.ID, c.ExternalID, c.Name, c.CanSync), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.ExternalID, c.Name, c.CanSync), + AddRow(c.ID, c.ExternalID, c.Name, c.CanSync), ) err = svc.UpdateByExternalId(ctx, c.ExternalID, &update) @@ -194,10 +193,10 @@ func TestUpdateByExternalId(t *testing.T) { c.CanSync = false update.CanSync = &c.CanSync - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.Name, c.CanSync), + AddRow(c.ID, c.Name, c.CanSync), ) err = svc.UpdateByExternalId(ctx, c.ExternalID, &update) @@ -208,12 +207,12 @@ func TestUpdateByExternalId(t *testing.T) { c.Name = "updated_name" update.Name = &c.Name - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(c.ID)). + pool.ExpectQuery("name: GetClient :one").WithArgs(c.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(c.ID), c.Name, c.CanSync), + AddRow(c.ID, c.Name, c.CanSync), ) - pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, database.MustToDBUUID(c.ID)). + pool.ExpectExec("name: UpdateClient :exec").WithArgs(*update.Name, c.ID). WillReturnResult(pgxmock.NewResult("", 1)) err = svc.UpdateByExternalId(ctx, c.ExternalID, &update) diff --git a/internal/collector/get.go b/internal/collector/get.go index 05a2d055..002591c7 100644 --- a/internal/collector/get.go +++ b/internal/collector/get.go @@ -3,7 +3,6 @@ package collector import ( "context" - "queryorchestration/internal/database" resultprocessor "queryorchestration/internal/query/result/processor" "github.com/google/uuid" @@ -19,7 +18,7 @@ func (s *Service) GetByClientExternalID(ctx context.Context, clientID string) (* } func (s *Service) GetByClientID(ctx context.Context, clientID uuid.UUID) (*Collector, error) { - dbColl, err := s.cfg.GetDBQueries().GetCollectorByClientID(ctx, database.MustToDBUUID(clientID)) + dbColl, err := s.cfg.GetDBQueries().GetCollectorByClientID(ctx, clientID) if err != nil { return nil, err } @@ -28,7 +27,7 @@ func (s *Service) GetByClientID(ctx context.Context, clientID uuid.UUID) (*Colle } func (s *Service) ListQueries(ctx context.Context, id uuid.UUID) ([]*resultprocessor.Query, error) { - queries, err := s.cfg.GetDBQueries().ListCollectorQueries(ctx, database.MustToDBUUID(id)) + queries, err := s.cfg.GetDBQueries().ListCollectorQueries(ctx, id) if err != nil { return nil, err } diff --git a/internal/collector/get_test.go b/internal/collector/get_test.go index 4152e7ad..1f2942ea 100644 --- a/internal/collector/get_test.go +++ b/internal/collector/get_test.go @@ -6,7 +6,6 @@ import ( "testing" "queryorchestration/internal/collector" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/serviceconfig" @@ -39,10 +38,10 @@ func TestGetByClientID(t *testing.T) { }, } - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(ogc.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(ogc.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(ogc.ClientID), ogc.MinCleanVersion, ogc.MinTextVersion, ogc.ActiveVersion, ogc.LatestVersion, []byte(fmt.Sprintf("{\"example_key\":\"%s\"}", ogc.Fields["example_key"].String()))), + AddRow(ogc.ClientID, ogc.MinCleanVersion, ogc.MinTextVersion, ogc.ActiveVersion, ogc.LatestVersion, []byte(fmt.Sprintf("{\"example_key\":\"%s\"}", ogc.Fields["example_key"].String()))), ) coll, err := svc.GetByClientID(ctx, ogc.ClientID) @@ -70,13 +69,14 @@ func TestListQueries(t *testing.T) { }, } - pool.ExpectQuery("name: ListCollectorQueries :many").WithArgs(database.MustToDBUUID(clientId)). + pool.ExpectQuery("name: ListCollectorQueries :many").WithArgs(clientId). WillReturnRows( pgxmock.NewRows([]string{"clientId", "queryId", "type", "queryVersion", "requiredIds"}). - AddRow(database.MustToDBUUID(clientId), database.MustToDBUUID(ogc[0].ID), repository.QuerytypeContextFull, int32(2), nil), + AddRow(clientId, &ogc[0].ID, repository.QuerytypeContextFull, int32(2), nil), ) qs, err := svc.ListQueries(ctx, clientId) require.NoError(t, err) - assert.EqualExportedValues(t, ogc, qs) + assert.Len(t, qs, 1) + assert.EqualExportedValues(t, *ogc[0], *qs[0]) } diff --git a/internal/collector/parse.go b/internal/collector/parse.go index 3e280b5b..fa301ee3 100644 --- a/internal/collector/parse.go +++ b/internal/collector/parse.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "github.com/google/uuid" @@ -27,7 +26,7 @@ func parseDBCollector(c *repository.Fullactivecollector) (*Collector, error) { } return &Collector{ - ClientID: database.MustToUUID(c.Clientid), + ClientID: c.Clientid, MinCleanVersion: c.Mincleanversion, MinTextVersion: c.Mintextversion, ActiveVersion: c.Activeversion, diff --git a/internal/collector/parse_test.go b/internal/collector/parse_test.go index 3a81d7b7..d1d9f795 100644 --- a/internal/collector/parse_test.go +++ b/internal/collector/parse_test.go @@ -4,7 +4,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "github.com/google/uuid" @@ -28,7 +27,7 @@ func TestParseDBCollector(t *testing.T) { }, } c, err = parseDBCollector(&repository.Fullactivecollector{ - Clientid: database.MustToDBUUID(ogc.ClientID), + Clientid: ogc.ClientID, Mincleanversion: ogc.MinCleanVersion, Mintextversion: ogc.MinTextVersion, Fields: []byte(fmt.Sprintf("{\"example_key\":\"%s\"}", ogc.Fields["example_key"])), @@ -39,7 +38,7 @@ func TestParseDBCollector(t *testing.T) { ogc.MinCleanVersion = 0 ogc.MinTextVersion = 0 c, err = parseDBCollector(&repository.Fullactivecollector{ - Clientid: database.MustToDBUUID(ogc.ClientID), + Clientid: ogc.ClientID, Fields: []byte(fmt.Sprintf("{\"example_key\":\"%s\"}", ogc.Fields["example_key"])), }) require.NoError(t, err) diff --git a/internal/collector/set/set.go b/internal/collector/set/set.go index d4072d57..a34d5fce 100644 --- a/internal/collector/set/set.go +++ b/internal/collector/set/set.go @@ -7,14 +7,12 @@ import ( clientsyncrunner "queryorchestration/api/clientSyncRunner" "queryorchestration/internal/collector" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig/build" "queryorchestration/internal/serviceconfig/queue" "queryorchestration/internal/validation" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" ) func (s *Service) SetByClientExternalId(ctx context.Context, id string, params *SetParams) error { @@ -23,7 +21,7 @@ func (s *Service) SetByClientExternalId(ctx context.Context, id string, params * return err } - err = s.SetByClientId(ctx, database.MustToUUID(client.ID), params) + err = s.SetByClientId(ctx, client.ID, params) if err != nil { return err } @@ -70,17 +68,17 @@ func (s *Service) informSet(ctx context.Context, update *dbSetParams) error { return s.cfg.SendToQueue(ctx, &queue.SendParams{ QueueURL: s.cfg.GetClientSyncURL(), Body: clientsyncrunner.Body{ - ID: database.MustToUUID(update.ClientID), + ID: update.ClientID, }, }) } type dbSetParams struct { - ClientID pgtype.UUID + ClientID uuid.UUID ActiveVersion *int32 MinCleanVersion *int64 MinTextVersion *int64 - Fields *map[string]pgtype.UUID + Fields *map[string]uuid.UUID } func (s *Service) getSetParams(ctx context.Context, id uuid.UUID, current *collector.Collector, params *SetParams) (*dbSetParams, error) { @@ -115,7 +113,7 @@ func (s *Service) getSetParams(ctx context.Context, id uuid.UUID, current *colle } return &dbSetParams{ - ClientID: database.MustToDBUUID(id), + ClientID: id, ActiveVersion: params.ActiveVersion, MinCleanVersion: params.MinCleanVersion, MinTextVersion: params.MinTextVersion, @@ -174,16 +172,16 @@ func (s *Service) normalizeActiveVersion(current *collector.Collector, params *S return nil } -func (s *Service) normalizeSetFieldsToDB(ctx context.Context, current map[string]uuid.UUID, ofields *map[string]uuid.UUID) (*map[string]pgtype.UUID, error) { +func (s *Service) normalizeSetFieldsToDB(ctx context.Context, current map[string]uuid.UUID, ofields *map[string]uuid.UUID) (*map[string]uuid.UUID, error) { if ofields == nil || *ofields == nil { return nil, nil } else if len(*ofields) == 0 { return nil, nil } - dbm := map[string]pgtype.UUID{} + dbm := map[string]uuid.UUID{} for name, id := range *ofields { - dbm[name] = database.MustToDBUUID(id) + dbm[name] = id } removeIDs := getRemoveFields(current, &dbm) @@ -282,8 +280,8 @@ func (s *Service) submitSet(ctx context.Context, current *collector.Collector, p return nil } -func getRemoveFields(current map[string]uuid.UUID, update *map[string]pgtype.UUID) []pgtype.UUID { - diff := []pgtype.UUID{} +func getRemoveFields(current map[string]uuid.UUID, update *map[string]uuid.UUID) []uuid.UUID { + diff := []uuid.UUID{} if update == nil { return diff } @@ -291,27 +289,27 @@ func getRemoveFields(current map[string]uuid.UUID, update *map[string]pgtype.UUI for ckey, cid := range current { found := false for ukey, uid := range *update { - if cid == database.MustToUUID(uid) && + if cid == uid && ckey == ukey { found = true } } if !found { - diff = append(diff, database.MustToDBUUID(cid)) + diff = append(diff, cid) } } return diff } -func getAddFields(current map[string]uuid.UUID, update *map[string]pgtype.UUID) map[string]pgtype.UUID { - diff := map[string]pgtype.UUID{} +func getAddFields(current map[string]uuid.UUID, update *map[string]uuid.UUID) map[string]uuid.UUID { + diff := map[string]uuid.UUID{} if update == nil { return diff } for ukey, uid := range *update { - if current[ukey] != database.MustToUUID(uid) { + if current[ukey] != uid { diff[ukey] = uid } } @@ -319,19 +317,19 @@ func getAddFields(current map[string]uuid.UUID, update *map[string]pgtype.UUID) return diff } -func (s *Service) normalizeFieldsToDB(ctx context.Context, ofields *map[string]uuid.UUID) (*map[string]pgtype.UUID, error) { +func (s *Service) normalizeFieldsToDB(ctx context.Context, ofields *map[string]uuid.UUID) (*map[string]uuid.UUID, error) { if ofields == nil || *ofields == nil { return nil, nil } else if len(*ofields) == 0 { return nil, nil } - dbm := map[string]pgtype.UUID{} + dbm := map[string]uuid.UUID{} for name, id := range *ofields { - dbm[name] = database.MustToDBUUID(id) + dbm[name] = id } - dbids := []pgtype.UUID{} + dbids := []uuid.UUID{} for _, id := range dbm { dbids = append(dbids, id) } diff --git a/internal/collector/set/set_test.go b/internal/collector/set/set_test.go index 74e695ce..c1f16ef1 100644 --- a/internal/collector/set/set_test.go +++ b/internal/collector/set/set_test.go @@ -7,7 +7,6 @@ import ( "queryorchestration/internal/collector" collectorset "queryorchestration/internal/collector/set" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/clientsync" @@ -55,20 +54,20 @@ func TestSet(t *testing.T) { MinCleanVersion: &mv, } - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(current.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(current.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(current.ClientID), current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), + AddRow(current.ClientID, current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), ) pool.ExpectBeginTx(pgx.TxOptions{}) rv := current.LatestVersion + 1 - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(rv), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(2)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *update.MinCleanVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, rv, *update.MinCleanVersion). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -96,20 +95,20 @@ func TestSet(t *testing.T) { MinCleanVersion: &mv, } - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(current.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(current.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(current.ClientID), current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), + AddRow(current.ClientID, current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), ) pool.ExpectBeginTx(pgx.TxOptions{}) rv := current.LatestVersion + 1 - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(rv), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(1)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *update.MinCleanVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, rv, *update.MinCleanVersion). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -161,22 +160,22 @@ func TestSetByExternalId(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(current.ClientID), externalId, "name", true), + AddRow(current.ClientID, externalId, "name", true), ) - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(current.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(current.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(current.ClientID), current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), + AddRow(current.ClientID, current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), ) pool.ExpectBeginTx(pgx.TxOptions{}) rv := current.LatestVersion + 1 - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(rv), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(2)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *update.MinCleanVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, rv, *update.MinCleanVersion). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -206,22 +205,22 @@ func TestSetByExternalId(t *testing.T) { pool.ExpectQuery("name: GetClientByExternalId :one").WithArgs(externalId).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "can_sync"}). - AddRow(database.MustToDBUUID(current.ClientID), externalId, "name", true), + AddRow(current.ClientID, externalId, "name", true), ) - pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(database.MustToDBUUID(current.ClientID)). + pool.ExpectQuery("name: GetCollectorByClientID :one").WithArgs(current.ClientID). WillReturnRows( pgxmock.NewRows([]string{"clientId", "minCleanVersion", "minTextVersion", "activeVersion", "latestVersion", "fields"}). - AddRow(database.MustToDBUUID(current.ClientID), current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), + AddRow(current.ClientID, current.MinCleanVersion, current.MinTextVersion, current.ActiveVersion, current.LatestVersion, []byte("")), ) pool.ExpectBeginTx(pgx.TxOptions{}) rv := current.LatestVersion + 1 - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(rv), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(1)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *update.MinCleanVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, rv, *update.MinCleanVersion). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() diff --git a/internal/collector/set/setprivate_test.go b/internal/collector/set/setprivate_test.go index f9c670b7..84773ca4 100644 --- a/internal/collector/set/setprivate_test.go +++ b/internal/collector/set/setprivate_test.go @@ -6,7 +6,6 @@ import ( "testing" "queryorchestration/internal/collector" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/clientsync" @@ -15,7 +14,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/google/uuid" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -60,7 +58,7 @@ func TestGetSetParams(t *testing.T) { }, } - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray([]uuid.UUID{(*params.Fields)["example_key"]})).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{(*params.Fields)["example_key"]}).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) @@ -70,12 +68,12 @@ func TestGetSetParams(t *testing.T) { dbparams, err := svc.getSetParams(ctx, clientId, ¤t, ¶ms) require.NoError(t, err) assert.EqualExportedValues(t, &dbSetParams{ - ClientID: database.MustToDBUUID(clientId), + ClientID: clientId, ActiveVersion: &aV, MinCleanVersion: &minCleanV, MinTextVersion: &minTextV, - Fields: &map[string]pgtype.UUID{ - "example_key": database.MustToDBUUID((*params.Fields)["example_key"]), + Fields: &map[string]uuid.UUID{ + "example_key": (*params.Fields)["example_key"], }, }, dbparams) @@ -191,38 +189,38 @@ func TestSubmitSet(t *testing.T) { } aV := int32(2) params := dbSetParams{ - ClientID: database.MustToDBUUID(current.ClientID), + ClientID: current.ClientID, ActiveVersion: &aV, MinCleanVersion: &minCleanV, MinTextVersion: &minTextV, - Fields: &map[string]pgtype.UUID{ - "example_key": database.MustToDBUUID(uuid.New()), - "second_key": database.MustToDBUUID(uuid.New()), - "changed_key": database.MustToDBUUID(current.Fields["original_key"]), - "og_key": database.MustToDBUUID(current.Fields["og_key"]), + Fields: &map[string]uuid.UUID{ + "example_key": uuid.New(), + "second_key": uuid.New(), + "changed_key": current.Fields["original_key"], + "og_key": current.Fields["og_key"], }, } pool.ExpectBeginTx(pgx.TxOptions{}) rv := int32(2) - pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(database.MustToDBUUID(current.ClientID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestCollectorVersion :one").WithArgs(current.ClientID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(rv), ) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(2)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *params.MinCleanVersion). + pool.ExpectExec("name: SetCollectorCleanVersion :exec").WithArgs(current.ClientID, rv, *params.MinCleanVersion). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetCollectorTextVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), rv, *params.MinTextVersion). + pool.ExpectExec("name: SetCollectorTextVersion :exec").WithArgs(current.ClientID, rv, *params.MinTextVersion). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: RemoveCollectorQuery :exec").WithArgs(&rv, database.MustToDBUUID(current.Fields["original_key"]), database.MustToDBUUID(current.ClientID)). + pool.ExpectExec("name: RemoveCollectorQuery :exec").WithArgs(&rv, current.Fields["original_key"], current.ClientID). WillReturnResult(pgxmock.NewResult("", 1)) pool.MatchExpectationsInOrder(false) - pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(database.MustToDBUUID(current.ClientID), "example_key", (*params.Fields)["example_key"], int32(2)). + pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(current.ClientID, "example_key", (*params.Fields)["example_key"], int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(database.MustToDBUUID(current.ClientID), "second_key", (*params.Fields)["second_key"], int32(2)). + pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(current.ClientID, "second_key", (*params.Fields)["second_key"], int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(database.MustToDBUUID(current.ClientID), "changed_key", (*params.Fields)["changed_key"], int32(2)). + pool.ExpectExec("name: AddCollectorQuery :exec").WithArgs(current.ClientID, "changed_key", (*params.Fields)["changed_key"], int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -254,12 +252,12 @@ func TestSubmitSet(t *testing.T) { } av := int32(2) params := dbSetParams{ - ClientID: database.MustToDBUUID(current.ClientID), + ClientID: current.ClientID, ActiveVersion: &av, } pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(database.MustToDBUUID(current.ClientID), int32(2)). + pool.ExpectExec("name: SetActiveCollectorVersion :exec").WithArgs(current.ClientID, int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -443,7 +441,7 @@ func TestNormalizeCodeVersions(t *testing.T) { func TestGetRemoveFields(t *testing.T) { current := map[string]uuid.UUID{} - var update *map[string]pgtype.UUID + var update *map[string]uuid.UUID remove := getRemoveFields(current, update) assert.Len(t, remove, 0) @@ -452,29 +450,29 @@ func TestGetRemoveFields(t *testing.T) { remove = getRemoveFields(current, update) assert.Len(t, remove, 0) - update = &map[string]pgtype.UUID{ - "b": database.MustToDBUUID(uuid.New()), + update = &map[string]uuid.UUID{ + "b": uuid.New(), } - (*update)["a"] = database.MustToDBUUID(current["a"]) + (*update)["a"] = current["a"] remove = getRemoveFields(current, update) assert.Len(t, remove, 0) - (*update)["a"] = database.MustToDBUUID(uuid.New()) + (*update)["a"] = uuid.New() remove = getRemoveFields(current, update) assert.Len(t, remove, 1) - assert.ElementsMatch(t, []pgtype.UUID{database.MustToDBUUID(current["a"])}, remove) + assert.ElementsMatch(t, []uuid.UUID{current["a"]}, remove) - (*update)["a"] = database.MustToDBUUID(uuid.Nil) - (*update)["c"] = database.MustToDBUUID(current["a"]) + (*update)["a"] = uuid.Nil + (*update)["c"] = current["a"] remove = getRemoveFields(current, update) assert.Len(t, remove, 1) - assert.ElementsMatch(t, []pgtype.UUID{database.MustToDBUUID(current["a"])}, remove) + assert.ElementsMatch(t, []uuid.UUID{current["a"]}, remove) } func TestGetAddFields(t *testing.T) { current := map[string]uuid.UUID{} - var update *map[string]pgtype.UUID + var update *map[string]uuid.UUID add := getAddFields(current, update) assert.Len(t, add, 0) @@ -483,34 +481,34 @@ func TestGetAddFields(t *testing.T) { add = getAddFields(current, update) assert.Len(t, add, 0) - update = &map[string]pgtype.UUID{} + update = &map[string]uuid.UUID{} add = getAddFields(current, update) assert.Len(t, add, 0) - (*update)["a"] = database.MustToDBUUID(current["a"]) + (*update)["a"] = current["a"] add = getAddFields(current, update) assert.Len(t, add, 0) - (*update)["a"] = database.MustToDBUUID(uuid.New()) + (*update)["a"] = uuid.New() add = getAddFields(current, update) assert.Len(t, add, 1) - assert.Equal(t, map[string]pgtype.UUID{ + assert.Equal(t, map[string]uuid.UUID{ "a": (*update)["a"], }, add) - (*update)["a"] = database.MustToDBUUID(current["a"]) - (*update)["b"] = database.MustToDBUUID(uuid.New()) + (*update)["a"] = current["a"] + (*update)["b"] = uuid.New() add = getAddFields(current, update) assert.Len(t, add, 1) - assert.Equal(t, map[string]pgtype.UUID{ + assert.Equal(t, map[string]uuid.UUID{ "b": (*update)["b"], }, add) current = map[string]uuid.UUID{} add = getAddFields(current, update) assert.Len(t, add, 2) - assert.Equal(t, map[string]pgtype.UUID{ + assert.Equal(t, map[string]uuid.UUID{ "b": (*update)["b"], "a": (*update)["a"], }, add) @@ -539,15 +537,15 @@ func TestNormalizeSetFieldsToDB(t *testing.T) { "example_key": uuid.New(), } - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray([]uuid.UUID{fields["example_key"]})).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{fields["example_key"]}).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) dbparams, err := svc.normalizeSetFieldsToDB(ctx, current, &fields) require.NoError(t, err) - assert.EqualExportedValues(t, &map[string]pgtype.UUID{ - "example_key": database.MustToDBUUID(fields["example_key"]), + assert.EqualExportedValues(t, &map[string]uuid.UUID{ + "example_key": fields["example_key"], }, dbparams) }) @@ -571,7 +569,7 @@ func TestNormalizeSetFieldsToDB(t *testing.T) { } fields["second_key"] = fields["example_key"] - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray([]uuid.UUID{fields["example_key"]})).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{fields["example_key"]}).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) @@ -620,7 +618,7 @@ func TestInformSet(t *testing.T) { av := int32(2) update := dbSetParams{ - ClientID: database.MustToDBUUID(uuid.New()), + ClientID: uuid.New(), ActiveVersion: &av, } @@ -652,7 +650,7 @@ func TestInformSet(t *testing.T) { svc := New(cfg, &Services{}) update := dbSetParams{ - ClientID: database.MustToDBUUID(uuid.New()), + ClientID: uuid.New(), } err = svc.informSet(ctx, &update) @@ -678,20 +676,20 @@ func TestNormalizeFieldsToDB(t *testing.T) { "example_key": uuid.New(), } - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray([]uuid.UUID{fields["example_key"]})).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{fields["example_key"]}).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) dbparams, err := svc.normalizeFieldsToDB(ctx, &fields) require.NoError(t, err) - assert.EqualExportedValues(t, &map[string]pgtype.UUID{ - "example_key": database.MustToDBUUID(fields["example_key"]), + assert.EqualExportedValues(t, &map[string]uuid.UUID{ + "example_key": fields["example_key"], }, dbparams) fields["second_key"] = fields["example_key"] - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray([]uuid.UUID{fields["example_key"]})).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs([]uuid.UUID{fields["example_key"]}).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) diff --git a/database/.gitignore b/internal/database/.gitignore similarity index 100% rename from database/.gitignore rename to internal/database/.gitignore diff --git a/database/database.md b/internal/database/database.md similarity index 100% rename from database/database.md rename to internal/database/database.md diff --git a/database/diagram.mmd b/internal/database/diagram.mmd similarity index 100% rename from database/diagram.mmd rename to internal/database/diagram.mmd diff --git a/internal/database/migrations/migrations.go b/internal/database/migrations.go similarity index 79% rename from internal/database/migrations/migrations.go rename to internal/database/migrations.go index 65049021..bf741636 100644 --- a/internal/database/migrations/migrations.go +++ b/internal/database/migrations.go @@ -1,11 +1,11 @@ -package migrations +package database import ( "context" "database/sql" + "embed" "fmt" "log/slog" - "path" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/database" @@ -13,6 +13,7 @@ import ( "github.com/golang-migrate/migrate/v4" _ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" + "github.com/golang-migrate/migrate/v4/source/iofs" _ "github.com/lib/pq" ) @@ -43,17 +44,21 @@ func createDB(cfg database.ConfigProvider) error { return nil } -func Run(ctx context.Context, cfg serviceconfig.ConfigProvider) error { +//go:embed migrations/*.up.sql +var migrations embed.FS + +func RunMigrations(ctx context.Context, cfg serviceconfig.ConfigProvider) error { err := createDB(cfg) if err != nil { return err } - migPath := "file://" + path.Join(cfg.GetBasePath(), "database/migrations") - m, err := migrate.New( - migPath, - cfg.GetDBURI(), - ) + source, err := iofs.New(migrations, "migrations") + if err != nil { + return err + } + + m, err := migrate.NewWithSourceInstance("iofs", source, cfg.GetDBURI()) if err != nil { return fmt.Errorf("failed to create migrate instance: %v", err) } diff --git a/database/migrations/00000000000001_extensions.down.sql b/internal/database/migrations/00000000000001_extensions.down.sql similarity index 100% rename from database/migrations/00000000000001_extensions.down.sql rename to internal/database/migrations/00000000000001_extensions.down.sql diff --git a/database/migrations/00000000000001_extensions.up.sql b/internal/database/migrations/00000000000001_extensions.up.sql similarity index 100% rename from database/migrations/00000000000001_extensions.up.sql rename to internal/database/migrations/00000000000001_extensions.up.sql diff --git a/database/migrations/00000000000002_queries.down.sql b/internal/database/migrations/00000000000002_queries.down.sql similarity index 100% rename from database/migrations/00000000000002_queries.down.sql rename to internal/database/migrations/00000000000002_queries.down.sql diff --git a/database/migrations/00000000000002_queries.up.sql b/internal/database/migrations/00000000000002_queries.up.sql similarity index 100% rename from database/migrations/00000000000002_queries.up.sql rename to internal/database/migrations/00000000000002_queries.up.sql diff --git a/database/migrations/00000000000003_clients.down.sql b/internal/database/migrations/00000000000003_clients.down.sql similarity index 100% rename from database/migrations/00000000000003_clients.down.sql rename to internal/database/migrations/00000000000003_clients.down.sql diff --git a/database/migrations/00000000000003_clients.up.sql b/internal/database/migrations/00000000000003_clients.up.sql similarity index 100% rename from database/migrations/00000000000003_clients.up.sql rename to internal/database/migrations/00000000000003_clients.up.sql diff --git a/database/migrations/00000000000004_collectors.down.sql b/internal/database/migrations/00000000000004_collectors.down.sql similarity index 100% rename from database/migrations/00000000000004_collectors.down.sql rename to internal/database/migrations/00000000000004_collectors.down.sql diff --git a/database/migrations/00000000000004_collectors.up.sql b/internal/database/migrations/00000000000004_collectors.up.sql similarity index 100% rename from database/migrations/00000000000004_collectors.up.sql rename to internal/database/migrations/00000000000004_collectors.up.sql diff --git a/database/migrations/00000000000005_documents.down.sql b/internal/database/migrations/00000000000005_documents.down.sql similarity index 100% rename from database/migrations/00000000000005_documents.down.sql rename to internal/database/migrations/00000000000005_documents.down.sql diff --git a/database/migrations/00000000000005_documents.up.sql b/internal/database/migrations/00000000000005_documents.up.sql similarity index 84% rename from database/migrations/00000000000005_documents.up.sql rename to internal/database/migrations/00000000000005_documents.up.sql index 13b30bb3..63674085 100644 --- a/database/migrations/00000000000005_documents.up.sql +++ b/internal/database/migrations/00000000000005_documents.up.sql @@ -52,8 +52,16 @@ CREATE TABLE documentCleanEntries ( CREATE TABLE documentTextExtractions ( id uuid primary key DEFAULT uuid_generate_v7(), cleanEntryId uuid not null, - version bigint not null, bucket text not null, key text not null, - foreign key (cleanEntryId) references documentCleans(id) + hash text not null, + foreign key (cleanEntryId) references documentCleans(id), + unique(cleanEntryId, hash) +); + +CREATE TABLE documentTextExtractionEntries ( + id uuid primary key DEFAULT uuid_generate_v7(), + textId uuid not null, + version bigint not null, + foreign key (textId) references documentTextExtractions(id) ); diff --git a/database/migrations/00000000000006_results.down.sql b/internal/database/migrations/00000000000006_results.down.sql similarity index 100% rename from database/migrations/00000000000006_results.down.sql rename to internal/database/migrations/00000000000006_results.down.sql diff --git a/database/migrations/00000000000006_results.up.sql b/internal/database/migrations/00000000000006_results.up.sql similarity index 100% rename from database/migrations/00000000000006_results.up.sql rename to internal/database/migrations/00000000000006_results.up.sql diff --git a/database/migrations/00000000000100_query_views.down.sql b/internal/database/migrations/00000000000100_query_views.down.sql similarity index 100% rename from database/migrations/00000000000100_query_views.down.sql rename to internal/database/migrations/00000000000100_query_views.down.sql diff --git a/database/migrations/00000000000100_query_views.up.sql b/internal/database/migrations/00000000000100_query_views.up.sql similarity index 100% rename from database/migrations/00000000000100_query_views.up.sql rename to internal/database/migrations/00000000000100_query_views.up.sql diff --git a/database/migrations/00000000000101_collector_views.down.sql b/internal/database/migrations/00000000000101_collector_views.down.sql similarity index 100% rename from database/migrations/00000000000101_collector_views.down.sql rename to internal/database/migrations/00000000000101_collector_views.down.sql diff --git a/database/migrations/00000000000101_collector_views.up.sql b/internal/database/migrations/00000000000101_collector_views.up.sql similarity index 100% rename from database/migrations/00000000000101_collector_views.up.sql rename to internal/database/migrations/00000000000101_collector_views.up.sql diff --git a/database/migrations/00000000000102_document_views.down.sql b/internal/database/migrations/00000000000102_document_views.down.sql similarity index 100% rename from database/migrations/00000000000102_document_views.down.sql rename to internal/database/migrations/00000000000102_document_views.down.sql diff --git a/database/migrations/00000000000102_document_views.up.sql b/internal/database/migrations/00000000000102_document_views.up.sql similarity index 97% rename from database/migrations/00000000000102_document_views.up.sql rename to internal/database/migrations/00000000000102_document_views.up.sql index 5493ded1..239eaf6a 100644 --- a/database/migrations/00000000000102_document_views.up.sql +++ b/internal/database/migrations/00000000000102_document_views.up.sql @@ -54,14 +54,16 @@ WITH RankedExtractions AS ( cc.documentId, dte.bucket, dte.key, - dte.version, + dte.hash, + dtee.version, dte.cleanEntryId, ROW_NUMBER() OVER (PARTITION BY cc.documentId ORDER BY dte.id DESC) as row_num FROM documents d JOIN currentCleanEntries cc on cc.documentId = d.id JOIN currentCollectorMinTextVersions ctv ON ctv.clientId = d.clientId JOIN documentTextExtractions dte ON dte.cleanEntryId = cc.id - AND dte.version >= ctv.minTextVersion + JOIN documentTextExtractionEntries dtee on dte.id = dtee.textId + AND dtee.version >= ctv.minTextVersion ) SELECT id, @@ -69,6 +71,7 @@ SELECT bucket, key, version, + hash, cleanEntryId FROM RankedExtractions WHERE row_num = 1; diff --git a/internal/database/migrations/migrations_test.go b/internal/database/migrations_test.go similarity index 77% rename from internal/database/migrations/migrations_test.go rename to internal/database/migrations_test.go index 2ab81bae..5ecf7add 100644 --- a/internal/database/migrations/migrations_test.go +++ b/internal/database/migrations_test.go @@ -1,12 +1,10 @@ -package migrations_test +package database_test import ( "context" - "os" - "path" "testing" - "queryorchestration/internal/database/migrations" + migrations "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/database" "queryorchestration/internal/test" @@ -23,14 +21,13 @@ func TestRunMigrations(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, }) defer cleanup() - err := migrations.Run(ctx, cfg) + err := migrations.RunMigrations(ctx, cfg) require.NoError(t, err) } @@ -39,7 +36,6 @@ func TestRunMigrationsNoDB(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) cfg.SetDBConfig(&database.DBConfig{ DBUser: "invalid_user", DBSecret: "invalid_pass", @@ -49,6 +45,6 @@ func TestRunMigrationsNoDB(t *testing.T) { DBNoSSL: true, }) - err := migrations.Run(ctx, cfg) + err := migrations.RunMigrations(ctx, cfg) assert.Error(t, err) } diff --git a/internal/database/migrations/migrationsprivate_test.go b/internal/database/migrationsprivate_test.go similarity index 93% rename from internal/database/migrations/migrationsprivate_test.go rename to internal/database/migrationsprivate_test.go index 4ce00140..e6574396 100644 --- a/internal/database/migrations/migrationsprivate_test.go +++ b/internal/database/migrationsprivate_test.go @@ -1,4 +1,4 @@ -package migrations +package database import ( "testing" diff --git a/internal/database/parseuuid.go b/internal/database/parseuuid.go deleted file mode 100644 index 239fa8ec..00000000 --- a/internal/database/parseuuid.go +++ /dev/null @@ -1,94 +0,0 @@ -package database - -import ( - "log" - - "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" -) - -func MustToDBUUIDArray(ids []uuid.UUID) []pgtype.UUID { - dbid, err := ToDBUUIDArray(ids) - if err != nil { - log.Panic(err) - } - - return dbid -} - -func ToDBUUIDArray(ids []uuid.UUID) ([]pgtype.UUID, error) { - dbIDs := []pgtype.UUID{} - for _, id := range ids { - uid, err := ToDBUUID(id) - if err != nil { - return nil, err - } - - if uid.Valid { - dbIDs = append(dbIDs, uid) - } - } - - return dbIDs, nil -} - -func MustToDBUUID(id uuid.UUID) pgtype.UUID { - dbid, err := ToDBUUID(id) - if err != nil { - log.Panic(err) - } - - return dbid -} - -func ToDBUUID(id uuid.UUID) (pgtype.UUID, error) { - var dbID pgtype.UUID - err := dbID.Scan(id.String()) - if err != nil { - return dbID, err - } - - if id == uuid.Nil { - dbID.Valid = false - } - - return dbID, nil -} - -func MustToUUID(dbid pgtype.UUID) uuid.UUID { - id, err := ToUUID(dbid) - if err != nil { - log.Panic(err) - } - - return id -} - -func ToUUID(id pgtype.UUID) (uuid.UUID, error) { - return uuid.FromBytes(id.Bytes[:]) -} - -func MustToUUIDArray(dbids []pgtype.UUID) []uuid.UUID { - ids, err := ToUUIDArray(dbids) - if err != nil { - log.Panic(err) - } - - return ids -} - -func ToUUIDArray(dbIDs []pgtype.UUID) ([]uuid.UUID, error) { - ids := []uuid.UUID{} - for _, id := range dbIDs { - uid, err := ToUUID(id) - if err != nil { - return nil, err - } - - if uid != uuid.Nil { - ids = append(ids, uid) - } - } - - return ids, nil -} diff --git a/internal/database/parseuuid_test.go b/internal/database/parseuuid_test.go deleted file mode 100644 index e18d42a6..00000000 --- a/internal/database/parseuuid_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package database_test - -import ( - "testing" - - "queryorchestration/internal/database" - - "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestToDBUUID(t *testing.T) { - id := uuid.New() - - dbID, err := database.ToDBUUID(id) - require.NoError(t, err) - - assert.True(t, dbID.Valid) - assert.Equal(t, id.String(), uuid.UUID(dbID.Bytes).String()) -} - -func TestToDBUUIDNil(t *testing.T) { - id := uuid.Nil - - dbID, err := database.ToDBUUID(id) - require.NoError(t, err) - - assert.False(t, dbID.Valid) - assert.Equal(t, id.String(), uuid.UUID(dbID.Bytes).String()) -} - -func TestToDBUUIDArray(t *testing.T) { - ids := []uuid.UUID{uuid.Nil, uuid.New()} - - dbIDs, err := database.ToDBUUIDArray(ids) - require.NoError(t, err) - - assert.Len(t, dbIDs, 1) - assert.ElementsMatch(t, []pgtype.UUID{database.MustToDBUUID(ids[1])}, dbIDs) -} - -func TestToUUID(t *testing.T) { - dbID, err := database.ToDBUUID(uuid.New()) - require.NoError(t, err) - - id, err := database.ToUUID(dbID) - require.NoError(t, err) - - assert.Equal(t, id.String(), uuid.UUID(dbID.Bytes).String()) -} - -func TestToUUIDArray(t *testing.T) { - ogIDs := []uuid.UUID{uuid.Nil, uuid.New()} - dbIDs := database.MustToDBUUIDArray(ogIDs) - - ids, err := database.ToUUIDArray(dbIDs) - require.NoError(t, err) - - assert.Len(t, ids, 1) - assert.ElementsMatch(t, []uuid.UUID{ogIDs[1]}, ids) -} diff --git a/database/queries/clean.sql b/internal/database/queries/clean.sql similarity index 100% rename from database/queries/clean.sql rename to internal/database/queries/clean.sql diff --git a/database/queries/client.sql b/internal/database/queries/client.sql similarity index 100% rename from database/queries/client.sql rename to internal/database/queries/client.sql diff --git a/database/queries/collector.sql b/internal/database/queries/collector.sql similarity index 100% rename from database/queries/collector.sql rename to internal/database/queries/collector.sql diff --git a/database/queries/document.sql b/internal/database/queries/document.sql similarity index 100% rename from database/queries/document.sql rename to internal/database/queries/document.sql diff --git a/database/queries/query.sql b/internal/database/queries/query.sql similarity index 100% rename from database/queries/query.sql rename to internal/database/queries/query.sql diff --git a/database/queries/result.sql b/internal/database/queries/result.sql similarity index 100% rename from database/queries/result.sql rename to internal/database/queries/result.sql diff --git a/internal/database/queries/text.sql b/internal/database/queries/text.sql new file mode 100644 index 00000000..9f177d1d --- /dev/null +++ b/internal/database/queries/text.sql @@ -0,0 +1,20 @@ +-- name: IsDocumentTextExtracted :one +SELECT EXISTS( + SELECT 1 FROM currentTextEntries WHERE documentId = @documentId +); + +-- name: GetDocumentTextExtractionByHash :one +SELECT id, documentId, bucket, key, version, hash, cleanEntryId + FROM currentTextEntries + WHERE cleanEntryId = @cleanEntryId and hash = @hash; + +-- name: AddDocumentText :one +INSERT INTO documentTextExtractions (bucket, key, cleanEntryId, hash) VALUES ($1, $2, $3, $4) returning id; + +-- name: AddDocumentTextEntry :exec +INSERT INTO documentTextExtractionEntries (textId, version) VALUES ($1, $2); + +-- name: GetTextEntryByDocId :one +SELECT id, documentId, bucket, key, version, hash, cleanEntryId + FROM currentTextEntries + WHERE documentId = @documentId; diff --git a/internal/database/repository/clean.sql.go b/internal/database/repository/clean.sql.go index ac8559d9..7988ffbb 100644 --- a/internal/database/repository/clean.sql.go +++ b/internal/database/repository/clean.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addDocumentClean = `-- name: AddDocumentClean :one @@ -16,7 +16,7 @@ INSERT INTO documentCleans (documentId, bucket, key, mimetype, fail) VALUES ($1, ` type AddDocumentCleanParams struct { - Documentid pgtype.UUID `db:"documentid"` + Documentid uuid.UUID `db:"documentid"` Bucket *string `db:"bucket"` Key *string `db:"key"` Mimetype NullCleanmimetype `db:"mimetype"` @@ -26,7 +26,7 @@ type AddDocumentCleanParams struct { // AddDocumentClean // // INSERT INTO documentCleans (documentId, bucket, key, mimetype, fail) VALUES ($1, $2, $3, $4, $5) returning id -func (q *Queries) AddDocumentClean(ctx context.Context, arg *AddDocumentCleanParams) (pgtype.UUID, error) { +func (q *Queries) AddDocumentClean(ctx context.Context, arg *AddDocumentCleanParams) (uuid.UUID, error) { row := q.db.QueryRow(ctx, addDocumentClean, arg.Documentid, arg.Bucket, @@ -34,7 +34,7 @@ func (q *Queries) AddDocumentClean(ctx context.Context, arg *AddDocumentCleanPar arg.Mimetype, arg.Fail, ) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -44,8 +44,8 @@ INSERT INTO documentCleanEntries (cleanId, version) VALUES ($1, $2) ` type AddDocumentCleanEntryParams struct { - Cleanid pgtype.UUID `db:"cleanid"` - Version int64 `db:"version"` + Cleanid uuid.UUID `db:"cleanid"` + Version int64 `db:"version"` } // AddDocumentCleanEntry @@ -67,7 +67,7 @@ SELECT id, documentId, bucket, key, version, mimetype, fail // SELECT id, documentId, bucket, key, version, mimetype, fail // FROM currentCleanEntries // WHERE id = $1 -func (q *Queries) GetCleanEntry(ctx context.Context, cleanid pgtype.UUID) (*Currentcleanentry, error) { +func (q *Queries) GetCleanEntry(ctx context.Context, cleanid uuid.UUID) (*Currentcleanentry, error) { row := q.db.QueryRow(ctx, getCleanEntry, cleanid) var i Currentcleanentry err := row.Scan( @@ -93,7 +93,7 @@ SELECT id, documentId, bucket, key, version, mimetype, fail // SELECT id, documentId, bucket, key, version, mimetype, fail // FROM currentCleanEntries // WHERE documentId = $1 -func (q *Queries) GetCleanEntryByDocId(ctx context.Context, documentid pgtype.UUID) (*Currentcleanentry, error) { +func (q *Queries) GetCleanEntryByDocId(ctx context.Context, documentid uuid.UUID) (*Currentcleanentry, error) { row := q.db.QueryRow(ctx, getCleanEntryByDocId, documentid) var i Currentcleanentry err := row.Scan( @@ -129,8 +129,8 @@ LIMIT 1 ` type GetMostRecentDocumentCleanEntryRow struct { - ID pgtype.UUID `db:"id"` - Documentid pgtype.UUID `db:"documentid"` + ID uuid.UUID `db:"id"` + Documentid uuid.UUID `db:"documentid"` Bucket *string `db:"bucket"` Key *string `db:"key"` Version int64 `db:"version"` @@ -157,7 +157,7 @@ type GetMostRecentDocumentCleanEntryRow struct { // JOIN documentCleanEntries dce ON dc.id = dce.cleanId // ORDER BY dc.id DESC, dce.id DESC // LIMIT 1 -func (q *Queries) GetMostRecentDocumentCleanEntry(ctx context.Context, documentid pgtype.UUID) (*GetMostRecentDocumentCleanEntryRow, error) { +func (q *Queries) GetMostRecentDocumentCleanEntry(ctx context.Context, documentid uuid.UUID) (*GetMostRecentDocumentCleanEntryRow, error) { row := q.db.QueryRow(ctx, getMostRecentDocumentCleanEntry, documentid) var i GetMostRecentDocumentCleanEntryRow err := row.Scan( @@ -183,7 +183,7 @@ SELECT EXISTS( // SELECT EXISTS( // SELECT 1 FROM currentCleanEntries WHERE documentId = $1 // ) -func (q *Queries) HasDocumentCleanEntry(ctx context.Context, documentid pgtype.UUID) (bool, error) { +func (q *Queries) HasDocumentCleanEntry(ctx context.Context, documentid uuid.UUID) (bool, error) { row := q.db.QueryRow(ctx, hasDocumentCleanEntry, documentid) var exists bool err := row.Scan(&exists) diff --git a/internal/database/repository/clean_test.go b/internal/database/repository/clean_test.go index 9d0cc655..47490cf0 100644 --- a/internal/database/repository/clean_test.go +++ b/internal/database/repository/clean_test.go @@ -2,8 +2,6 @@ package repository_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" @@ -22,7 +20,6 @@ func TestClean(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, diff --git a/internal/database/repository/client.sql.go b/internal/database/repository/client.sql.go index 842969e8..1ca4665c 100644 --- a/internal/database/repository/client.sql.go +++ b/internal/database/repository/client.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addClientCanSync = `-- name: AddClientCanSync :exec @@ -16,8 +16,8 @@ INSERT INTO clientCanSync (canSync, clientId) VALUES ($1, $2) ` type AddClientCanSyncParams struct { - Cansync bool `db:"cansync"` - Clientid pgtype.UUID `db:"clientid"` + Cansync bool `db:"cansync"` + Clientid uuid.UUID `db:"clientid"` } // AddClientCanSync @@ -40,9 +40,9 @@ type CreateClientParams struct { // CreateClient // // INSERT INTO clients (externalId, name) VALUES ($1, $2) RETURNING id -func (q *Queries) CreateClient(ctx context.Context, arg *CreateClientParams) (pgtype.UUID, error) { +func (q *Queries) CreateClient(ctx context.Context, arg *CreateClientParams) (uuid.UUID, error) { row := q.db.QueryRow(ctx, createClient, arg.Externalid, arg.Name) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -54,7 +54,7 @@ SELECT id, externalid, name, cansync FROM fullClients WHERE id = $1 // GetClient // // SELECT id, externalid, name, cansync FROM fullClients WHERE id = $1 -func (q *Queries) GetClient(ctx context.Context, id pgtype.UUID) (*Fullclient, error) { +func (q *Queries) GetClient(ctx context.Context, id uuid.UUID) (*Fullclient, error) { row := q.db.QueryRow(ctx, getClient, id) var i Fullclient err := row.Scan( @@ -278,7 +278,7 @@ SELECT ( // NOT EXISTS (SELECT 1 FROM dependency_check) // )::bool // )::bool as is_synced -func (q *Queries) IsClientSynced(ctx context.Context, dollar_1 pgtype.UUID) (bool, error) { +func (q *Queries) IsClientSynced(ctx context.Context, dollar_1 *uuid.UUID) (bool, error) { row := q.db.QueryRow(ctx, isClientSynced, dollar_1) var is_synced bool err := row.Scan(&is_synced) @@ -290,8 +290,8 @@ UPDATE clients SET name = $1 WHERE id = $2 ` type UpdateClientParams struct { - Name string `db:"name"` - ID pgtype.UUID `db:"id"` + Name string `db:"name"` + ID uuid.UUID `db:"id"` } // UpdateClient diff --git a/internal/database/repository/client_test.go b/internal/database/repository/client_test.go index 471469b0..8b8a0cb8 100644 --- a/internal/database/repository/client_test.go +++ b/internal/database/repository/client_test.go @@ -2,8 +2,6 @@ package repository_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" @@ -22,7 +20,6 @@ func TestClient(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, diff --git a/internal/database/repository/collector.sql.go b/internal/database/repository/collector.sql.go index 6323899c..b1f80a34 100644 --- a/internal/database/repository/collector.sql.go +++ b/internal/database/repository/collector.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addCollectorQuery = `-- name: AddCollectorQuery :exec @@ -16,10 +16,10 @@ INSERT INTO collectorQueries (clientId, name, queryId, addedVersion) VALUES ($1, ` type AddCollectorQueryParams struct { - Clientid pgtype.UUID `db:"clientid"` - Name string `db:"name"` - Queryid pgtype.UUID `db:"queryid"` - Addedversion int32 `db:"addedversion"` + Clientid uuid.UUID `db:"clientid"` + Name string `db:"name"` + Queryid uuid.UUID `db:"queryid"` + Addedversion int32 `db:"addedversion"` } // AddCollectorQuery @@ -42,7 +42,7 @@ INSERT INTO collectorVersions (clientId) VALUES ($1) RETURNING id // AddLatestCollectorVersion // // INSERT INTO collectorVersions (clientId) VALUES ($1) RETURNING id -func (q *Queries) AddLatestCollectorVersion(ctx context.Context, clientid pgtype.UUID) (int32, error) { +func (q *Queries) AddLatestCollectorVersion(ctx context.Context, clientid uuid.UUID) (int32, error) { row := q.db.QueryRow(ctx, addLatestCollectorVersion, clientid) var id int32 err := row.Scan(&id) @@ -87,7 +87,7 @@ SELECT clientid, mincleanversion, mintextversion, activeversion, latestversion, // GetCollectorByClientID // // SELECT clientid, mincleanversion, mintextversion, activeversion, latestversion, fields FROM fullActiveCollectors WHERE clientId = $1 LIMIT 1 -func (q *Queries) GetCollectorByClientID(ctx context.Context, clientid pgtype.UUID) (*Fullactivecollector, error) { +func (q *Queries) GetCollectorByClientID(ctx context.Context, clientid uuid.UUID) (*Fullactivecollector, error) { row := q.db.QueryRow(ctx, getCollectorByClientID, clientid) var i Fullactivecollector err := row.Scan( @@ -108,7 +108,7 @@ SELECT clientid, queryid, type, queryversion, requiredids FROM collectorQueryDep // ListCollectorQueries // // SELECT clientid, queryid, type, queryversion, requiredids FROM collectorQueryDependencyTree WHERE clientId = $1 -func (q *Queries) ListCollectorQueries(ctx context.Context, clientid pgtype.UUID) ([]*Collectorquerydependencytree, error) { +func (q *Queries) ListCollectorQueries(ctx context.Context, clientid uuid.UUID) ([]*Collectorquerydependencytree, error) { rows, err := q.db.Query(ctx, listCollectorQueries, clientid) if err != nil { return nil, err @@ -139,9 +139,9 @@ UPDATE collectorQueries SET removedVersion = $1 WHERE queryId = $2 and clientId ` type RemoveCollectorQueryParams struct { - Removedversion *int32 `db:"removedversion"` - Queryid pgtype.UUID `db:"queryid"` - Clientid pgtype.UUID `db:"clientid"` + Removedversion *int32 `db:"removedversion"` + Queryid uuid.UUID `db:"queryid"` + Clientid uuid.UUID `db:"clientid"` } // RemoveCollectorQuery @@ -157,8 +157,8 @@ INSERT INTO collectorActiveVersions (clientId, versionId) VALUES ($1, $2) ` type SetActiveCollectorVersionParams struct { - Clientid pgtype.UUID `db:"clientid"` - Versionid int32 `db:"versionid"` + Clientid uuid.UUID `db:"clientid"` + Versionid int32 `db:"versionid"` } // SetActiveCollectorVersion @@ -174,9 +174,9 @@ INSERT INTO collectorMinCleanVersions (clientId, addedVersion, versionId) VALUES ` type SetCollectorCleanVersionParams struct { - Clientid pgtype.UUID `db:"clientid"` - Addedversion int32 `db:"addedversion"` - Versionid int64 `db:"versionid"` + Clientid uuid.UUID `db:"clientid"` + Addedversion int32 `db:"addedversion"` + Versionid int64 `db:"versionid"` } // SetCollectorCleanVersion @@ -192,9 +192,9 @@ INSERT INTO collectorMinTextVersions (clientId, addedVersion, versionId) VALUES ` type SetCollectorTextVersionParams struct { - Clientid pgtype.UUID `db:"clientid"` - Addedversion int32 `db:"addedversion"` - Versionid int64 `db:"versionid"` + Clientid uuid.UUID `db:"clientid"` + Addedversion int32 `db:"addedversion"` + Versionid int64 `db:"versionid"` } // SetCollectorTextVersion diff --git a/internal/database/repository/collector_test.go b/internal/database/repository/collector_test.go index 75756fe2..bc442633 100644 --- a/internal/database/repository/collector_test.go +++ b/internal/database/repository/collector_test.go @@ -3,16 +3,13 @@ package repository_test import ( "context" "fmt" - "os" - "path" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/test" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -25,7 +22,6 @@ func TestCollector(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -124,7 +120,7 @@ func TestCollector(t *testing.T) { Mintextversion: minTextVersion, Activeversion: 1, Latestversion: 1, - Fields: []byte(fmt.Sprintf("{\"example_key\": \"%s\"}", database.MustToUUID(jsonId).String())), + Fields: []byte(fmt.Sprintf("{\"example_key\": \"%s\"}", jsonId.String())), }, coll) err = queries.SetCollectorCleanVersion(ctx, &repository.SetCollectorCleanVersionParams{ @@ -142,7 +138,7 @@ func TestCollector(t *testing.T) { Mintextversion: minTextVersion, Activeversion: 1, Latestversion: 1, - Fields: []byte(fmt.Sprintf("{\"example_key\": \"%s\"}", database.MustToUUID(jsonId).String())), + Fields: []byte(fmt.Sprintf("{\"example_key\": \"%s\"}", jsonId.String())), }, coll) qs, err := queries.ListCollectorQueries(ctx, clientId) @@ -151,17 +147,17 @@ func TestCollector(t *testing.T) { assert.ElementsMatch(t, []*repository.Collectorquerydependencytree{ { Clientid: clientId, - Queryid: jsonId, + Queryid: &jsonId, Queryversion: 1, Type: repository.QuerytypeJsonExtractor, - Requiredids: []pgtype.UUID{contextId}, + Requiredids: []uuid.UUID{contextId}, }, { Clientid: clientId, - Queryid: contextId, + Queryid: &contextId, Queryversion: 0, Type: repository.QuerytypeContextFull, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, }, qs) diff --git a/internal/database/repository/document.sql.go b/internal/database/repository/document.sql.go index 0e77edbe..b2cef408 100644 --- a/internal/database/repository/document.sql.go +++ b/internal/database/repository/document.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addDocumentEntry = `-- name: AddDocumentEntry :exec @@ -16,9 +16,9 @@ INSERT INTO documentEntries (documentId, bucket, key) VALUES ($1, $2, $3) ` type AddDocumentEntryParams struct { - Documentid pgtype.UUID `db:"documentid"` - Bucket string `db:"bucket"` - Key string `db:"key"` + Documentid uuid.UUID `db:"documentid"` + Bucket string `db:"bucket"` + Key string `db:"key"` } // AddDocumentEntry @@ -34,16 +34,16 @@ INSERT INTO documents (clientId, hash) VALUES ($1, $2) RETURNING id ` type CreateDocumentParams struct { - Clientid pgtype.UUID `db:"clientid"` - Hash string `db:"hash"` + Clientid uuid.UUID `db:"clientid"` + Hash string `db:"hash"` } // CreateDocument // // INSERT INTO documents (clientId, hash) VALUES ($1, $2) RETURNING id -func (q *Queries) CreateDocument(ctx context.Context, arg *CreateDocumentParams) (pgtype.UUID, error) { +func (q *Queries) CreateDocument(ctx context.Context, arg *CreateDocumentParams) (uuid.UUID, error) { row := q.db.QueryRow(ctx, createDocument, arg.Clientid, arg.Hash) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -53,15 +53,15 @@ SELECT documentId, bucket, key FROM documentEntries WHERE documentId = $1 ORDER ` type GetDocumentEntryRow struct { - Documentid pgtype.UUID `db:"documentid"` - Bucket string `db:"bucket"` - Key string `db:"key"` + Documentid uuid.UUID `db:"documentid"` + Bucket string `db:"bucket"` + Key string `db:"key"` } // GetDocumentEntry // // SELECT documentId, bucket, key FROM documentEntries WHERE documentId = $1 ORDER BY id DESC LIMIT 1 -func (q *Queries) GetDocumentEntry(ctx context.Context, documentid pgtype.UUID) (*GetDocumentEntryRow, error) { +func (q *Queries) GetDocumentEntry(ctx context.Context, documentid uuid.UUID) (*GetDocumentEntryRow, error) { row := q.db.QueryRow(ctx, getDocumentEntry, documentid) var i GetDocumentEntryRow err := row.Scan(&i.Documentid, &i.Bucket, &i.Key) @@ -97,10 +97,10 @@ GROUP BY d.id, c.externalId, d.hash ` type GetDocumentExternalRow struct { - ID pgtype.UUID `db:"id"` - Clientid string `db:"clientid"` - Hash string `db:"hash"` - Fields []byte `db:"fields"` + ID uuid.UUID `db:"id"` + Clientid string `db:"clientid"` + Hash string `db:"hash"` + Fields []byte `db:"fields"` } // GetDocumentExternal @@ -130,7 +130,7 @@ type GetDocumentExternalRow struct { // JOIN clients AS c ON c.id = d.clientId // LEFT JOIN namedResults AS r ON d.id = r.id // GROUP BY d.id, c.externalId, d.hash -func (q *Queries) GetDocumentExternal(ctx context.Context, documentid pgtype.UUID) (*GetDocumentExternalRow, error) { +func (q *Queries) GetDocumentExternal(ctx context.Context, documentid *uuid.UUID) (*GetDocumentExternalRow, error) { row := q.db.QueryRow(ctx, getDocumentExternal, documentid) var i GetDocumentExternalRow err := row.Scan( @@ -147,16 +147,16 @@ SELECT id FROM documents WHERE hash = $1 and clientId = $2 ` type GetDocumentIDByHashParams struct { - Hash string `db:"hash"` - Clientid pgtype.UUID `db:"clientid"` + Hash string `db:"hash"` + Clientid uuid.UUID `db:"clientid"` } // GetDocumentIDByHash // // SELECT id FROM documents WHERE hash = $1 and clientId = $2 -func (q *Queries) GetDocumentIDByHash(ctx context.Context, arg *GetDocumentIDByHashParams) (pgtype.UUID, error) { +func (q *Queries) GetDocumentIDByHash(ctx context.Context, arg *GetDocumentIDByHashParams) (uuid.UUID, error) { row := q.db.QueryRow(ctx, getDocumentIDByHash, arg.Hash, arg.Clientid) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -168,7 +168,7 @@ SELECT id, clientId, hash FROM documents WHERE id = $1 // GetDocumentSummary // // SELECT id, clientId, hash FROM documents WHERE id = $1 -func (q *Queries) GetDocumentSummary(ctx context.Context, id pgtype.UUID) (*Document, error) { +func (q *Queries) GetDocumentSummary(ctx context.Context, id uuid.UUID) (*Document, error) { row := q.db.QueryRow(ctx, getDocumentSummary, id) var i Document err := row.Scan(&i.ID, &i.Clientid, &i.Hash) @@ -180,14 +180,14 @@ SELECT id, totalCount FROM listDocumentIDs($1, $2, $3) ` type ListDocumentIDsBatchParams struct { - Clientid pgtype.UUID `db:"clientid"` - Batchsize int32 `db:"batchsize"` - Pageoffset int32 `db:"pageoffset"` + Clientid uuid.UUID `db:"clientid"` + Batchsize int32 `db:"batchsize"` + Pageoffset int32 `db:"pageoffset"` } type ListDocumentIDsBatchRow struct { - ID pgtype.UUID `db:"id"` - Totalcount *int64 `db:"totalcount"` + ID *uuid.UUID `db:"id"` + Totalcount *int64 `db:"totalcount"` } // ListDocumentIDsBatch @@ -223,8 +223,8 @@ SELECT d.id, d.hash ` type ListDocumentsByClientExternalIdRow struct { - ID pgtype.UUID `db:"id"` - Hash string `db:"hash"` + ID uuid.UUID `db:"id"` + Hash string `db:"hash"` } // ListDocumentsByClientExternalId diff --git a/internal/database/repository/document_test.go b/internal/database/repository/document_test.go index 62d4deaf..0d7c3857 100644 --- a/internal/database/repository/document_test.go +++ b/internal/database/repository/document_test.go @@ -19,7 +19,7 @@ func TestDocument(t *testing.T) { ctx := context.Background() cfg := &serviceconfig.BaseConfig{} - test.SetCfgProviderWithBasePath(t, cfg, "../../..") + test.SetCfgProvider(t, cfg) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -126,7 +126,7 @@ func TestDocument(t *testing.T) { Hash: hash, }, doc) - docext, err := queries.GetDocumentExternal(ctx, id) + docext, err := queries.GetDocumentExternal(ctx, &id) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: id, diff --git a/internal/database/repository/models.go b/internal/database/repository/models.go index 10fe26fe..9ce2b233 100644 --- a/internal/database/repository/models.go +++ b/internal/database/repository/models.go @@ -8,6 +8,7 @@ import ( "database/sql/driver" "fmt" + "github.com/google/uuid" "github.com/jackc/pgx/v5/pgtype" ) @@ -179,75 +180,75 @@ func (e Querytype) Valid() bool { } type Client struct { - ID pgtype.UUID `db:"id"` - Externalid string `db:"externalid"` - Name string `db:"name"` + ID uuid.UUID `db:"id"` + Externalid string `db:"externalid"` + Name string `db:"name"` } type Clientcansync struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Cansync bool `db:"cansync"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Cansync bool `db:"cansync"` } type Collectoractiveversion struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Versionid int32 `db:"versionid"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Versionid int32 `db:"versionid"` } type Collectorcurrentactiveversion struct { - Clientid pgtype.UUID `db:"clientid"` - Activeversion int32 `db:"activeversion"` + Clientid uuid.UUID `db:"clientid"` + Activeversion int32 `db:"activeversion"` } type Collectorlatestversion struct { - Clientid pgtype.UUID `db:"clientid"` - Latestversion int32 `db:"latestversion"` + Clientid uuid.UUID `db:"clientid"` + Latestversion int32 `db:"latestversion"` } type Collectormincleanversion struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Versionid int64 `db:"versionid"` - Addedversion int32 `db:"addedversion"` - Removedversion *int32 `db:"removedversion"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Versionid int64 `db:"versionid"` + Addedversion int32 `db:"addedversion"` + Removedversion *int32 `db:"removedversion"` } type Collectormintextversion struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Versionid int64 `db:"versionid"` - Addedversion int32 `db:"addedversion"` - Removedversion *int32 `db:"removedversion"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Versionid int64 `db:"versionid"` + Addedversion int32 `db:"addedversion"` + Removedversion *int32 `db:"removedversion"` } type Collectorquery struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Name string `db:"name"` - Queryid pgtype.UUID `db:"queryid"` - Addedversion int32 `db:"addedversion"` - Removedversion *int32 `db:"removedversion"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Name string `db:"name"` + Queryid uuid.UUID `db:"queryid"` + Addedversion int32 `db:"addedversion"` + Removedversion *int32 `db:"removedversion"` } type Collectorquerydependencytree struct { - Clientid pgtype.UUID `db:"clientid"` - Queryid pgtype.UUID `db:"queryid"` - Type Querytype `db:"type"` - Queryversion int32 `db:"queryversion"` - Requiredids []pgtype.UUID `db:"requiredids"` + Clientid uuid.UUID `db:"clientid"` + Queryid *uuid.UUID `db:"queryid"` + Type Querytype `db:"type"` + Queryversion int32 `db:"queryversion"` + Requiredids []uuid.UUID `db:"requiredids"` } type Collectorversion struct { - Clientid pgtype.UUID `db:"clientid"` + Clientid uuid.UUID `db:"clientid"` ID int32 `db:"id"` Addedat pgtype.Timestamp `db:"addedat"` } type Currentcleanentry struct { - ID pgtype.UUID `db:"id"` - Documentid pgtype.UUID `db:"documentid"` + ID uuid.UUID `db:"id"` + Documentid uuid.UUID `db:"documentid"` Bucket *string `db:"bucket"` Key *string `db:"key"` Version int64 `db:"version"` @@ -256,49 +257,50 @@ type Currentcleanentry struct { } type Currentclientcansync struct { - Clientid pgtype.UUID `db:"clientid"` - Cansync bool `db:"cansync"` + Clientid uuid.UUID `db:"clientid"` + Cansync bool `db:"cansync"` } type Currentcollectormincleanversion struct { - Clientid pgtype.UUID `db:"clientid"` - Mincleanversion int64 `db:"mincleanversion"` + Clientid uuid.UUID `db:"clientid"` + Mincleanversion int64 `db:"mincleanversion"` } type Currentcollectormintextversion struct { - Clientid pgtype.UUID `db:"clientid"` - Mintextversion int64 `db:"mintextversion"` + Clientid uuid.UUID `db:"clientid"` + Mintextversion int64 `db:"mintextversion"` } type Currentcollectorqueriesjsonagg struct { - Clientid pgtype.UUID `db:"clientid"` - Fields []byte `db:"fields"` + Clientid uuid.UUID `db:"clientid"` + Fields []byte `db:"fields"` } type Currentcollectorquery struct { - Clientid pgtype.UUID `db:"clientid"` - Name *string `db:"name"` - Queryid pgtype.UUID `db:"queryid"` + Clientid uuid.UUID `db:"clientid"` + Name *string `db:"name"` + Queryid *uuid.UUID `db:"queryid"` } type Currenttextentry struct { - ID pgtype.UUID `db:"id"` - Documentid pgtype.UUID `db:"documentid"` - Bucket string `db:"bucket"` - Key string `db:"key"` - Version int64 `db:"version"` - Cleanentryid pgtype.UUID `db:"cleanentryid"` + ID uuid.UUID `db:"id"` + Documentid uuid.UUID `db:"documentid"` + Bucket string `db:"bucket"` + Key string `db:"key"` + Version int64 `db:"version"` + Hash string `db:"hash"` + Cleanentryid uuid.UUID `db:"cleanentryid"` } type Document struct { - ID pgtype.UUID `db:"id"` - Clientid pgtype.UUID `db:"clientid"` - Hash string `db:"hash"` + ID uuid.UUID `db:"id"` + Clientid uuid.UUID `db:"clientid"` + Hash string `db:"hash"` } type Documentclean struct { - ID pgtype.UUID `db:"id"` - Documentid pgtype.UUID `db:"documentid"` + ID uuid.UUID `db:"id"` + Documentid uuid.UUID `db:"documentid"` Bucket *string `db:"bucket"` Key *string `db:"key"` Mimetype NullCleanmimetype `db:"mimetype"` @@ -306,123 +308,129 @@ type Documentclean struct { } type Documentcleanentry struct { - ID pgtype.UUID `db:"id"` - Cleanid pgtype.UUID `db:"cleanid"` - Version int64 `db:"version"` + ID uuid.UUID `db:"id"` + Cleanid uuid.UUID `db:"cleanid"` + Version int64 `db:"version"` } type Documententry struct { - ID pgtype.UUID `db:"id"` - Documentid pgtype.UUID `db:"documentid"` - Bucket string `db:"bucket"` - Key string `db:"key"` + ID uuid.UUID `db:"id"` + Documentid uuid.UUID `db:"documentid"` + Bucket string `db:"bucket"` + Key string `db:"key"` } type Documenttextextraction struct { - ID pgtype.UUID `db:"id"` - Cleanentryid pgtype.UUID `db:"cleanentryid"` - Version int64 `db:"version"` - Bucket string `db:"bucket"` - Key string `db:"key"` + ID uuid.UUID `db:"id"` + Cleanentryid uuid.UUID `db:"cleanentryid"` + Bucket string `db:"bucket"` + Key string `db:"key"` + Hash string `db:"hash"` +} + +type Documenttextextractionentry struct { + ID uuid.UUID `db:"id"` + Textid uuid.UUID `db:"textid"` + Version int64 `db:"version"` } type Fullactivecollector struct { - Clientid pgtype.UUID `db:"clientid"` - Mincleanversion int64 `db:"mincleanversion"` - Mintextversion int64 `db:"mintextversion"` - Activeversion int32 `db:"activeversion"` - Latestversion int32 `db:"latestversion"` - Fields []byte `db:"fields"` + Clientid uuid.UUID `db:"clientid"` + Mincleanversion int64 `db:"mincleanversion"` + Mintextversion int64 `db:"mintextversion"` + Activeversion int32 `db:"activeversion"` + Latestversion int32 `db:"latestversion"` + Fields []byte `db:"fields"` } type Fullactivequery struct { - ID pgtype.UUID `db:"id"` - Type Querytype `db:"type"` - Activeversion int32 `db:"activeversion"` - Latestversion int32 `db:"latestversion"` - Config []byte `db:"config"` - Requiredids []pgtype.UUID `db:"requiredids"` + ID uuid.UUID `db:"id"` + Type Querytype `db:"type"` + Activeversion int32 `db:"activeversion"` + Latestversion int32 `db:"latestversion"` + Config []byte `db:"config"` + Requiredids []uuid.UUID `db:"requiredids"` } type Fullclient struct { - ID pgtype.UUID `db:"id"` - Externalid string `db:"externalid"` - Name string `db:"name"` - Cansync bool `db:"cansync"` + ID uuid.UUID `db:"id"` + Externalid string `db:"externalid"` + Name string `db:"name"` + Cansync bool `db:"cansync"` } type Query struct { - ID pgtype.UUID `db:"id"` - Type Querytype `db:"type"` + ID uuid.UUID `db:"id"` + Type Querytype `db:"type"` } type Queryactivedependency struct { - ID pgtype.UUID `db:"id"` - Requiredqueryid pgtype.UUID `db:"requiredqueryid"` + ID uuid.UUID `db:"id"` + Requiredqueryid *uuid.UUID `db:"requiredqueryid"` } type Queryactiveversion struct { - ID pgtype.UUID `db:"id"` - Queryid pgtype.UUID `db:"queryid"` - Versionid int32 `db:"versionid"` + ID uuid.UUID `db:"id"` + Queryid uuid.UUID `db:"queryid"` + Versionid int32 `db:"versionid"` } type Queryconfig struct { - ID pgtype.UUID `db:"id"` - Queryid pgtype.UUID `db:"queryid"` - Config []byte `db:"config"` - Addedversion int32 `db:"addedversion"` - Removedversion *int32 `db:"removedversion"` + ID uuid.UUID `db:"id"` + Queryid uuid.UUID `db:"queryid"` + Config []byte `db:"config"` + Addedversion int32 `db:"addedversion"` + Removedversion *int32 `db:"removedversion"` } type Querycurrentactiveversion struct { - Queryid pgtype.UUID `db:"queryid"` - Activeversion int32 `db:"activeversion"` + Queryid uuid.UUID `db:"queryid"` + Activeversion int32 `db:"activeversion"` } type Querycurrentconfig struct { - Queryid pgtype.UUID `db:"queryid"` - Config []byte `db:"config"` + Queryid uuid.UUID `db:"queryid"` + Config []byte `db:"config"` } type Querycurrentrequiredid struct { - Queryid pgtype.UUID `db:"queryid"` - Requiredqueryid pgtype.UUID `db:"requiredqueryid"` + Queryid uuid.UUID `db:"queryid"` + Requiredqueryid *uuid.UUID `db:"requiredqueryid"` } type Querycurrentrequiredidsagg struct { - Queryid pgtype.UUID `db:"queryid"` - Requiredids []pgtype.UUID `db:"requiredids"` + Queryid uuid.UUID `db:"queryid"` + Requiredids []uuid.UUID `db:"requiredids"` } type Querylatestversion struct { - Queryid pgtype.UUID `db:"queryid"` - Latestversion int32 `db:"latestversion"` + Queryid uuid.UUID `db:"queryid"` + Latestversion int32 `db:"latestversion"` } type Queryversion struct { - Queryid pgtype.UUID `db:"queryid"` + Queryid uuid.UUID `db:"queryid"` ID int32 `db:"id"` Addedat pgtype.Timestamp `db:"addedat"` } type Requiredquery struct { - ID pgtype.UUID `db:"id"` - Queryid pgtype.UUID `db:"queryid"` - Requiredqueryid pgtype.UUID `db:"requiredqueryid"` - Addedversion int32 `db:"addedversion"` - Removedversion *int32 `db:"removedversion"` + ID uuid.UUID `db:"id"` + Queryid uuid.UUID `db:"queryid"` + Requiredqueryid uuid.UUID `db:"requiredqueryid"` + Addedversion int32 `db:"addedversion"` + Removedversion *int32 `db:"removedversion"` } type Result struct { - ID pgtype.UUID `db:"id"` - Textentryid pgtype.UUID `db:"textentryid"` - Queryid pgtype.UUID `db:"queryid"` - Value string `db:"value"` - Queryversion int32 `db:"queryversion"` + ID uuid.UUID `db:"id"` + Textentryid uuid.UUID `db:"textentryid"` + Queryid uuid.UUID `db:"queryid"` + Value string `db:"value"` + Queryversion int32 `db:"queryversion"` } type Resultdependency struct { - Resultid pgtype.UUID `db:"resultid"` - Requiredresultid pgtype.UUID `db:"requiredresultid"` + Resultid uuid.UUID `db:"resultid"` + Requiredresultid uuid.UUID `db:"requiredresultid"` } diff --git a/internal/database/repository/query.sql.go b/internal/database/repository/query.sql.go index c9dc4fbf..7367af0a 100644 --- a/internal/database/repository/query.sql.go +++ b/internal/database/repository/query.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addActiveQueryVersion = `-- name: AddActiveQueryVersion :exec @@ -16,8 +16,8 @@ INSERT INTO queryActiveVersions (queryId, versionId) VALUES ($1, $2) ` type AddActiveQueryVersionParams struct { - Queryid pgtype.UUID `db:"queryid"` - Versionid int32 `db:"versionid"` + Queryid uuid.UUID `db:"queryid"` + Versionid int32 `db:"versionid"` } // AddActiveQueryVersion @@ -35,7 +35,7 @@ INSERT INTO queryVersions (queryId) VALUES ($1) RETURNING id // AddLatestQueryVersion // // INSERT INTO queryVersions (queryId) VALUES ($1) RETURNING id -func (q *Queries) AddLatestQueryVersion(ctx context.Context, queryid pgtype.UUID) (int32, error) { +func (q *Queries) AddLatestQueryVersion(ctx context.Context, queryid uuid.UUID) (int32, error) { row := q.db.QueryRow(ctx, addLatestQueryVersion, queryid) var id int32 err := row.Scan(&id) @@ -47,9 +47,9 @@ INSERT INTO requiredQueries (queryId, requiredQueryId, addedVersion) VALUES ($1, ` type AddRequiredQueryParams struct { - Queryid pgtype.UUID `db:"queryid"` - Requiredqueryid pgtype.UUID `db:"requiredqueryid"` - Addedversion int32 `db:"addedversion"` + Queryid uuid.UUID `db:"queryid"` + Requiredqueryid uuid.UUID `db:"requiredqueryid"` + Addedversion int32 `db:"addedversion"` } // AddRequiredQuery @@ -71,7 +71,7 @@ SELECT COUNT(*) = COUNT(DISTINCT id) AS all_exist // SELECT COUNT(*) = COUNT(DISTINCT id) AS all_exist // FROM unnest($1::uuid[]) AS input_id // LEFT JOIN queries ON input_id = queries.id -func (q *Queries) AllQueriesExist(ctx context.Context, dollar_1 []pgtype.UUID) (bool, error) { +func (q *Queries) AllQueriesExist(ctx context.Context, dollar_1 []uuid.UUID) (bool, error) { row := q.db.QueryRow(ctx, allQueriesExist, dollar_1) var all_exist bool err := row.Scan(&all_exist) @@ -85,9 +85,9 @@ INSERT INTO queries (type) VALUES ($1) RETURNING id // CreateQuery // // INSERT INTO queries (type) VALUES ($1) RETURNING id -func (q *Queries) CreateQuery(ctx context.Context, type_ Querytype) (pgtype.UUID, error) { +func (q *Queries) CreateQuery(ctx context.Context, type_ Querytype) (uuid.UUID, error) { row := q.db.QueryRow(ctx, createQuery, type_) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -99,7 +99,7 @@ SELECT config FROM queryCurrentConfigs where queryId = $1 // GetActiveQueryConfig // // SELECT config FROM queryCurrentConfigs where queryId = $1 -func (q *Queries) GetActiveQueryConfig(ctx context.Context, queryid pgtype.UUID) ([]byte, error) { +func (q *Queries) GetActiveQueryConfig(ctx context.Context, queryid uuid.UUID) ([]byte, error) { row := q.db.QueryRow(ctx, getActiveQueryConfig, queryid) var config []byte err := row.Scan(&config) @@ -113,7 +113,7 @@ SELECT id, type, activeversion, latestversion, config, requiredids FROM fullActi // GetQuery // // SELECT id, type, activeversion, latestversion, config, requiredids FROM fullActiveQueries WHERE id = $1 -func (q *Queries) GetQuery(ctx context.Context, id pgtype.UUID) (*Fullactivequery, error) { +func (q *Queries) GetQuery(ctx context.Context, id uuid.UUID) (*Fullactivequery, error) { row := q.db.QueryRow(ctx, getQuery, id) var i Fullactivequery err := row.Scan( @@ -161,17 +161,17 @@ SELECT DISTINCT q.id, q.type, ` type GetQueryWithVersionParams struct { - ID pgtype.UUID `db:"id"` - Version *int32 `db:"version"` + ID *uuid.UUID `db:"id"` + Version *int32 `db:"version"` } type GetQueryWithVersionRow struct { - ID pgtype.UUID `db:"id"` - Type Querytype `db:"type"` - Activeversion int32 `db:"activeversion"` - Latestversion int32 `db:"latestversion"` - Config []byte `db:"config"` - Requiredids []pgtype.UUID `db:"requiredids"` + ID uuid.UUID `db:"id"` + Type Querytype `db:"type"` + Activeversion int32 `db:"activeversion"` + Latestversion int32 `db:"latestversion"` + Config []byte `db:"config"` + Requiredids []uuid.UUID `db:"requiredids"` } // GetQueryWithVersion @@ -230,8 +230,8 @@ SELECT EXISTS ( ` type IsQueryInDependencyTreeParams struct { - Requiredqueryids []pgtype.UUID `db:"requiredqueryids"` - Queryid pgtype.UUID `db:"queryid"` + Requiredqueryids []uuid.UUID `db:"requiredqueryids"` + Queryid *uuid.UUID `db:"queryid"` } // IsQueryInDependencyTree @@ -290,7 +290,7 @@ SELECT id, type, activeversion, latestversion, config, requiredids FROM fullActi // ListQueriesById // // SELECT id, type, activeversion, latestversion, config, requiredids FROM fullActiveQueries WHERE id = any($1) -func (q *Queries) ListQueriesById(ctx context.Context, id []pgtype.UUID) ([]*Fullactivequery, error) { +func (q *Queries) ListQueriesById(ctx context.Context, id []uuid.UUID) ([]*Fullactivequery, error) { rows, err := q.db.Query(ctx, listQueriesById, id) if err != nil { return nil, err @@ -324,15 +324,15 @@ SELECT clientId FROM collectorQueryDependencyTree WHERE queryId = $1 // ListQueryClientIDs // // SELECT clientId FROM collectorQueryDependencyTree WHERE queryId = $1 -func (q *Queries) ListQueryClientIDs(ctx context.Context, queryid pgtype.UUID) ([]pgtype.UUID, error) { +func (q *Queries) ListQueryClientIDs(ctx context.Context, queryid *uuid.UUID) ([]uuid.UUID, error) { rows, err := q.db.Query(ctx, listQueryClientIDs, queryid) if err != nil { return nil, err } defer rows.Close() - items := []pgtype.UUID{} + items := []uuid.UUID{} for rows.Next() { - var clientid pgtype.UUID + var clientid uuid.UUID if err := rows.Scan(&clientid); err != nil { return nil, err } @@ -356,8 +356,8 @@ SELECT dt.queryId ` type ListQueryDirectDependentsByDocumentIDParams struct { - Queryid pgtype.UUID `db:"queryid"` - Documentid pgtype.UUID `db:"documentid"` + Queryid uuid.UUID `db:"queryid"` + Documentid uuid.UUID `db:"documentid"` } // ListQueryDirectDependentsByDocumentID @@ -370,15 +370,15 @@ type ListQueryDirectDependentsByDocumentIDParams struct { // JOIN collectorQueryDependencyTree as dt // on d.clientId = dt.clientId // and $1 = any(dt.requiredIds) -func (q *Queries) ListQueryDirectDependentsByDocumentID(ctx context.Context, arg *ListQueryDirectDependentsByDocumentIDParams) ([]pgtype.UUID, error) { +func (q *Queries) ListQueryDirectDependentsByDocumentID(ctx context.Context, arg *ListQueryDirectDependentsByDocumentIDParams) ([]*uuid.UUID, error) { rows, err := q.db.Query(ctx, listQueryDirectDependentsByDocumentID, arg.Queryid, arg.Documentid) if err != nil { return nil, err } defer rows.Close() - items := []pgtype.UUID{} + items := []*uuid.UUID{} for rows.Next() { - var queryid pgtype.UUID + var queryid *uuid.UUID if err := rows.Scan(&queryid); err != nil { return nil, err } @@ -395,9 +395,9 @@ UPDATE requiredQueries SET removedVersion = $1 WHERE requiredQueryId = $2 and qu ` type RemoveRequiredQueryParams struct { - Removedversion *int32 `db:"removedversion"` - Requiredqueryid pgtype.UUID `db:"requiredqueryid"` - Queryid pgtype.UUID `db:"queryid"` + Removedversion *int32 `db:"removedversion"` + Requiredqueryid uuid.UUID `db:"requiredqueryid"` + Queryid uuid.UUID `db:"queryid"` } // RemoveRequiredQuery @@ -413,9 +413,9 @@ INSERT INTO queryConfigs (queryId, config, addedVersion) VALUES ($1, $2, $3) ` type SetQueryConfigParams struct { - Queryid pgtype.UUID `db:"queryid"` - Config []byte `db:"config"` - Addedversion int32 `db:"addedversion"` + Queryid uuid.UUID `db:"queryid"` + Config []byte `db:"config"` + Addedversion int32 `db:"addedversion"` } // SetQueryConfig diff --git a/internal/database/repository/query_test.go b/internal/database/repository/query_test.go index 9ddb7d03..ecdbbc20 100644 --- a/internal/database/repository/query_test.go +++ b/internal/database/repository/query_test.go @@ -2,17 +2,13 @@ package repository_test import ( "context" - "os" - "path" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/test" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -25,7 +21,6 @@ func TestQueries(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -36,7 +31,6 @@ func TestQueries(t *testing.T) { contextQueryID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeContextFull)) require.NoError(t, err) - assert.True(t, contextQueryID.Valid) contextQuery, err := queries.GetQuery(ctx, contextQueryID) require.NoError(t, err) @@ -46,7 +40,7 @@ func TestQueries(t *testing.T) { Activeversion: 0, Latestversion: 0, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, contextQuery) ctxVersion, err := queries.AddLatestQueryVersion(ctx, contextQueryID) @@ -61,12 +55,11 @@ func TestQueries(t *testing.T) { Activeversion: 0, Latestversion: 1, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, contextQuery) jsonQueryID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeJsonExtractor)) require.NoError(t, err) - assert.True(t, jsonQueryID.Valid) jsonQuery, err := queries.GetQuery(ctx, jsonQueryID) require.NoError(t, err) @@ -76,7 +69,7 @@ func TestQueries(t *testing.T) { Activeversion: 0, Latestversion: 0, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, jsonQuery) jsonVersion, err := queries.AddLatestQueryVersion(ctx, jsonQueryID) @@ -91,7 +84,7 @@ func TestQueries(t *testing.T) { Activeversion: 0, Latestversion: 1, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, jsonQuery) err = queries.AddActiveQueryVersion(ctx, &repository.AddActiveQueryVersionParams{ @@ -108,7 +101,7 @@ func TestQueries(t *testing.T) { Activeversion: 1, Latestversion: 1, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, jsonQuery) jsonConfig := []byte("{\"path\": \"example_path\"}") @@ -128,7 +121,7 @@ func TestQueries(t *testing.T) { Activeversion: 1, Latestversion: 1, Config: nil, - Requiredids: []pgtype.UUID{contextQueryID}, + Requiredids: []uuid.UUID{contextQueryID}, }, jsonQuery) jsonVersion, err = queries.AddLatestQueryVersion(ctx, jsonQueryID) @@ -143,7 +136,7 @@ func TestQueries(t *testing.T) { Activeversion: 1, Latestversion: 2, Config: nil, - Requiredids: []pgtype.UUID{contextQueryID}, + Requiredids: []uuid.UUID{contextQueryID}, }, jsonQuery) removeV := int32(2) @@ -194,12 +187,12 @@ func TestQueries(t *testing.T) { Activeversion: 2, Latestversion: 2, Config: jsonQueryConfig, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, jsonQuery) v := int32(1) versionedQuery, err := queries.GetQueryWithVersion(ctx, &repository.GetQueryWithVersionParams{ - ID: jsonQueryID, + ID: &jsonQueryID, Version: &v, }) require.NoError(t, err) @@ -209,26 +202,26 @@ func TestQueries(t *testing.T) { Activeversion: 2, Latestversion: 2, Config: jsonConfig, - Requiredids: []pgtype.UUID{contextQueryID}, + Requiredids: []uuid.UUID{contextQueryID}, }, versionedQuery) - all_exist, err := queries.AllQueriesExist(ctx, []pgtype.UUID{}) + all_exist, err := queries.AllQueriesExist(ctx, []uuid.UUID{}) require.NoError(t, err) assert.True(t, all_exist) - all_exist, err = queries.AllQueriesExist(ctx, []pgtype.UUID{database.MustToDBUUID(uuid.New())}) + all_exist, err = queries.AllQueriesExist(ctx, []uuid.UUID{uuid.New()}) require.NoError(t, err) assert.False(t, all_exist) - all_exist, err = queries.AllQueriesExist(ctx, []pgtype.UUID{jsonQueryID}) + all_exist, err = queries.AllQueriesExist(ctx, []uuid.UUID{jsonQueryID}) require.NoError(t, err) assert.True(t, all_exist) - all_exist, err = queries.AllQueriesExist(ctx, []pgtype.UUID{jsonQueryID, contextQueryID}) + all_exist, err = queries.AllQueriesExist(ctx, []uuid.UUID{jsonQueryID, contextQueryID}) require.NoError(t, err) assert.True(t, all_exist) - all_exist, err = queries.AllQueriesExist(ctx, []pgtype.UUID{jsonQueryID, database.MustToDBUUID(uuid.New())}) + all_exist, err = queries.AllQueriesExist(ctx, []uuid.UUID{jsonQueryID, uuid.New()}) require.NoError(t, err) assert.False(t, all_exist) } @@ -241,7 +234,6 @@ func TestQueryDependencyTree(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -283,7 +275,7 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []uuid.UUID{}, dependents) jsonQueryID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeJsonExtractor)) require.NoError(t, err) @@ -300,7 +292,7 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []uuid.UUID{}, dependents) err = queries.AddRequiredQuery(ctx, &repository.AddRequiredQueryParams{ Queryid: jsonQueryID, @@ -314,13 +306,13 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []uuid.UUID{}, dependents) err = queries.AddCollectorQuery(ctx, &repository.AddCollectorQueryParams{ Clientid: clientID, @@ -335,13 +327,13 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, dependents) secondJsonQueryID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeJsonExtractor)) require.NoError(t, err) @@ -358,13 +350,13 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, dependents) err = queries.AddRequiredQuery(ctx, &repository.AddRequiredQueryParams{ Queryid: secondJsonQueryID, @@ -378,19 +370,19 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: secondJsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, dependents) err = queries.AddCollectorQuery(ctx, &repository.AddCollectorQueryParams{ Clientid: clientID, @@ -405,51 +397,51 @@ func TestQueryDependencyTree(t *testing.T) { Queryid: secondJsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: jsonQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{secondJsonQueryID}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{&secondJsonQueryID}, dependents) dependents, err = queries.ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ Documentid: docID, Queryid: contextQueryID, }) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, dependents) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, dependents) isdependent, err := queries.IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: jsonQueryID, - Requiredqueryids: []pgtype.UUID{contextQueryID}, + Queryid: &jsonQueryID, + Requiredqueryids: []uuid.UUID{contextQueryID}, }) require.NoError(t, err) assert.False(t, isdependent) isdependent, err = queries.IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: jsonQueryID, - Requiredqueryids: []pgtype.UUID{secondJsonQueryID}, + Queryid: &jsonQueryID, + Requiredqueryids: []uuid.UUID{secondJsonQueryID}, }) require.NoError(t, err) assert.True(t, isdependent) isdependent, err = queries.IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: jsonQueryID, - Requiredqueryids: []pgtype.UUID{jsonQueryID}, + Queryid: &jsonQueryID, + Requiredqueryids: []uuid.UUID{jsonQueryID}, }) require.NoError(t, err) assert.True(t, isdependent) isdependent, err = queries.IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: secondJsonQueryID, - Requiredqueryids: []pgtype.UUID{jsonQueryID, contextQueryID}, + Queryid: &secondJsonQueryID, + Requiredqueryids: []uuid.UUID{jsonQueryID, contextQueryID}, }) require.NoError(t, err) assert.False(t, isdependent) isdependent, err = queries.IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: contextQueryID, - Requiredqueryids: []pgtype.UUID{jsonQueryID, secondJsonQueryID}, + Queryid: &contextQueryID, + Requiredqueryids: []uuid.UUID{jsonQueryID, secondJsonQueryID}, }) require.NoError(t, err) assert.True(t, isdependent) @@ -463,7 +455,6 @@ func TestQueriesList(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -488,7 +479,7 @@ func TestQueriesList(t *testing.T) { Activeversion: 0, Latestversion: 0, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, { ID: contextQueryID, @@ -496,11 +487,11 @@ func TestQueriesList(t *testing.T) { Activeversion: 0, Latestversion: 0, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, }, qs) - qs, err = queries.ListQueriesById(ctx, []pgtype.UUID{jsonQueryID}) + qs, err = queries.ListQueriesById(ctx, []uuid.UUID{jsonQueryID}) require.NoError(t, err) assert.Len(t, qs, 1) assert.ElementsMatch(t, []*repository.Fullactivequery{ @@ -510,7 +501,7 @@ func TestQueriesList(t *testing.T) { Activeversion: 0, Latestversion: 0, Config: nil, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, }, }, qs) } @@ -523,7 +514,6 @@ func TestListQueryClients(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -535,9 +525,9 @@ func TestListQueryClients(t *testing.T) { contextID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeContextFull)) require.NoError(t, err) - clients, err := queries.ListQueryClientIDs(ctx, contextID) + clients, err := queries.ListQueryClientIDs(ctx, &contextID) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{}, clients) + assert.ElementsMatch(t, []uuid.UUID{}, clients) clientOneID, err := queries.CreateClient(ctx, &repository.CreateClientParams{ Name: "example_client", @@ -559,9 +549,9 @@ func TestListQueryClients(t *testing.T) { }) require.NoError(t, err) - clients, err = queries.ListQueryClientIDs(ctx, contextID) + clients, err = queries.ListQueryClientIDs(ctx, &contextID) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{clientOneID}, clients) + assert.ElementsMatch(t, []uuid.UUID{clientOneID}, clients) clientTwoID, err := queries.CreateClient(ctx, &repository.CreateClientParams{ Name: "example_client_dos", @@ -583,9 +573,9 @@ func TestListQueryClients(t *testing.T) { }) require.NoError(t, err) - clients, err = queries.ListQueryClientIDs(ctx, contextID) + clients, err = queries.ListQueryClientIDs(ctx, &contextID) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{clientOneID, clientTwoID}, clients) + assert.ElementsMatch(t, []uuid.UUID{clientOneID, clientTwoID}, clients) jsonID, err := queries.CreateQuery(ctx, repository.Querytype(repository.QuerytypeJsonExtractor)) require.NoError(t, err) @@ -605,7 +595,7 @@ func TestListQueryClients(t *testing.T) { }) require.NoError(t, err) - clients, err = queries.ListQueryClientIDs(ctx, jsonID) + clients, err = queries.ListQueryClientIDs(ctx, &jsonID) require.NoError(t, err) - assert.ElementsMatch(t, []pgtype.UUID{clientOneID}, clients) + assert.ElementsMatch(t, []uuid.UUID{clientOneID}, clients) } diff --git a/internal/database/repository/result.sql.go b/internal/database/repository/result.sql.go index 423b847f..107fc275 100644 --- a/internal/database/repository/result.sql.go +++ b/internal/database/repository/result.sql.go @@ -8,7 +8,7 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) const addResult = `-- name: AddResult :one @@ -16,23 +16,23 @@ INSERT INTO results (queryId, value, textEntryId, queryVersion) VALUES ($1, $2, ` type AddResultParams struct { - Queryid pgtype.UUID `db:"queryid"` - Value string `db:"value"` - Textentryid pgtype.UUID `db:"textentryid"` - Queryversion int32 `db:"queryversion"` + Queryid uuid.UUID `db:"queryid"` + Value string `db:"value"` + Textentryid uuid.UUID `db:"textentryid"` + Queryversion int32 `db:"queryversion"` } // AddResult // // INSERT INTO results (queryId, value, textEntryId, queryVersion) VALUES ($1, $2, $3, $4) returning id -func (q *Queries) AddResult(ctx context.Context, arg *AddResultParams) (pgtype.UUID, error) { +func (q *Queries) AddResult(ctx context.Context, arg *AddResultParams) (uuid.UUID, error) { row := q.db.QueryRow(ctx, addResult, arg.Queryid, arg.Value, arg.Textentryid, arg.Queryversion, ) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } @@ -42,8 +42,8 @@ INSERT INTO resultDependencies (resultId, requiredResultId) VALUES ($1, $2) ` type AddResultDependencyParams struct { - Resultid pgtype.UUID `db:"resultid"` - Requiredresultid pgtype.UUID `db:"requiredresultid"` + Resultid uuid.UUID `db:"resultid"` + Requiredresultid uuid.UUID `db:"requiredresultid"` } // AddResultDependency @@ -70,14 +70,14 @@ SELECT r.id, r.value ` type GetResultValueWithVersionParams struct { - Queryid pgtype.UUID `db:"queryid"` - Queryversion *int32 `db:"queryversion"` - Documentid pgtype.UUID `db:"documentid"` + Queryid *uuid.UUID `db:"queryid"` + Queryversion *int32 `db:"queryversion"` + Documentid *uuid.UUID `db:"documentid"` } type GetResultValueWithVersionRow struct { - ID pgtype.UUID `db:"id"` - Value *string `db:"value"` + ID *uuid.UUID `db:"id"` + Value *string `db:"value"` } // GetResultValueWithVersion @@ -148,16 +148,16 @@ WHERE rowNumber = 1 ` type ListQueryRequirementValuesParams struct { - Queryid pgtype.UUID `db:"queryid"` - Version *int32 `db:"version"` - Documentid pgtype.UUID `db:"documentid"` + Queryid *uuid.UUID `db:"queryid"` + Version *int32 `db:"version"` + Documentid *uuid.UUID `db:"documentid"` } type ListQueryRequirementValuesRow struct { - ID pgtype.UUID `db:"id"` - Queryid pgtype.UUID `db:"queryid"` - Type Querytype `db:"type"` - Value *string `db:"value"` + ID *uuid.UUID `db:"id"` + Queryid uuid.UUID `db:"queryid"` + Type Querytype `db:"type"` + Value *string `db:"value"` } // ListQueryRequirementValues @@ -271,15 +271,15 @@ SELECT DISTINCT queryId FROM unsyncedQueries as baseuq // WHERE NOT EXISTS ( // SELECT 1 FROM unsyncedQueries as uq WHERE uq.queryId = any(baseuq.requiredIds) // ) -func (q *Queries) ListUnsyncedNoDepsQueriesByDocId(ctx context.Context, dollar_1 pgtype.UUID) ([]pgtype.UUID, error) { +func (q *Queries) ListUnsyncedNoDepsQueriesByDocId(ctx context.Context, dollar_1 *uuid.UUID) ([]*uuid.UUID, error) { rows, err := q.db.Query(ctx, listUnsyncedNoDepsQueriesByDocId, dollar_1) if err != nil { return nil, err } defer rows.Close() - items := []pgtype.UUID{} + items := []*uuid.UUID{} for rows.Next() { - var queryid pgtype.UUID + var queryid *uuid.UUID if err := rows.Scan(&queryid); err != nil { return nil, err } diff --git a/internal/database/repository/result_test.go b/internal/database/repository/result_test.go index c5983e13..83dfbc7e 100644 --- a/internal/database/repository/result_test.go +++ b/internal/database/repository/result_test.go @@ -2,15 +2,13 @@ package repository_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/test" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +21,6 @@ func TestResults(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -48,7 +45,7 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err := queries.IsClientSynced(ctx, clientId) + issynced, err := queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, issynced) @@ -58,7 +55,7 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, issynced) @@ -70,7 +67,7 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, issynced) @@ -92,19 +89,24 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, issynced) - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanid, + Hash: "example", + }) + require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, issynced) @@ -116,7 +118,7 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, issynced) @@ -130,15 +132,15 @@ func TestResults(t *testing.T) { }) require.NoError(t, err) - issynced, err = queries.IsClientSynced(ctx, clientId) + issynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, issynced) qv := int32(1) res, err := queries.GetResultValueWithVersion(ctx, &repository.GetResultValueWithVersionParams{ - Queryid: jsonQueryID, + Queryid: &jsonQueryID, Queryversion: &qv, - Documentid: documentID, + Documentid: &documentID, }) require.NoError(t, err) assert.NotNil(t, res.Value) @@ -153,7 +155,6 @@ func TestResultValues(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -213,15 +214,15 @@ func TestResultValues(t *testing.T) { require.NoError(t, err) qResults, err := queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentID, + Queryid: &jsonQueryID, + Documentid: &documentID, Version: &jsonVersion, }) require.NoError(t, err) assert.Len(t, qResults, 0) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentTwoID, + Queryid: &jsonQueryID, + Documentid: &documentTwoID, Version: &jsonVersion, }) require.NoError(t, err) @@ -252,11 +253,16 @@ func TestResultValues(t *testing.T) { Version: 1, }) require.NoError(t, err) - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanid, + Hash: "example", + }) + require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, }) require.NoError(t, err) @@ -271,8 +277,8 @@ func TestResultValues(t *testing.T) { require.NoError(t, err) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentID, + Queryid: &jsonQueryID, + Documentid: &documentID, Version: &jsonVersion, }) require.NoError(t, err) @@ -280,11 +286,10 @@ func TestResultValues(t *testing.T) { assert.Equal(t, contextQueryID, qResults[0].Queryid) assert.Equal(t, repository.QuerytypeContextFull, qResults[0].Type) assert.Equal(t, "context_value_1", *qResults[0].Value) - assert.NotEqual(t, pgtype.UUID{}, qResults[0].ID) - assert.True(t, qResults[0].ID.Valid) + assert.NotEqual(t, uuid.UUID{}, qResults[0].ID) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentTwoID, + Queryid: &jsonQueryID, + Documentid: &documentTwoID, Version: &jsonVersion, }) require.NoError(t, err) @@ -299,8 +304,8 @@ func TestResultValues(t *testing.T) { require.NoError(t, err) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentID, + Queryid: &jsonQueryID, + Documentid: &documentID, Version: &jsonVersion, }) require.NoError(t, err) @@ -308,8 +313,7 @@ func TestResultValues(t *testing.T) { assert.Equal(t, contextQueryID, qResults[0].Queryid) assert.Equal(t, repository.QuerytypeContextFull, qResults[0].Type) assert.Equal(t, "context_value_1", *qResults[0].Value) - assert.NotEqual(t, pgtype.UUID{}, qResults[0].ID) - assert.True(t, qResults[0].ID.Valid) + assert.NotEqual(t, uuid.UUID{}, qResults[0].ID) _, err = queries.AddResult(ctx, &repository.AddResultParams{ Queryid: contextQueryID, @@ -320,8 +324,8 @@ func TestResultValues(t *testing.T) { require.NoError(t, err) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentID, + Queryid: &jsonQueryID, + Documentid: &documentID, Version: &jsonVersion, }) require.NoError(t, err) @@ -329,8 +333,7 @@ func TestResultValues(t *testing.T) { assert.Equal(t, contextQueryID, qResults[0].Queryid) assert.Equal(t, repository.QuerytypeContextFull, qResults[0].Type) assert.Equal(t, "context_value_3", *qResults[0].Value) - assert.NotEqual(t, pgtype.UUID{}, qResults[0].ID) - assert.True(t, qResults[0].ID.Valid) + assert.NotEqual(t, uuid.UUID{}, qResults[0].ID) _, err = queries.AddResult(ctx, &repository.AddResultParams{ Queryid: jsonQueryID, @@ -341,8 +344,8 @@ func TestResultValues(t *testing.T) { require.NoError(t, err) qResults, err = queries.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: jsonQueryID, - Documentid: documentID, + Queryid: &jsonQueryID, + Documentid: &documentID, Version: &jsonVersion, }) require.NoError(t, err) @@ -350,8 +353,7 @@ func TestResultValues(t *testing.T) { assert.Equal(t, contextQueryID, qResults[0].Queryid) assert.Equal(t, repository.QuerytypeContextFull, qResults[0].Type) assert.Equal(t, "context_value_3", *qResults[0].Value) - assert.NotEqual(t, pgtype.UUID{}, qResults[0].ID) - assert.True(t, qResults[0].ID.Valid) + assert.NotEqual(t, uuid.UUID{}, qResults[0].ID) } func TestUnsyncedNoDepsQueries(t *testing.T) { @@ -362,7 +364,6 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -427,10 +428,10 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err := queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err := queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) @@ -452,26 +453,30 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanid, }) require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, + }) + require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 1) - assert.ElementsMatch(t, []pgtype.UUID{contextQueryID}, qs) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + assert.ElementsMatch(t, []*uuid.UUID{&contextQueryID}, qs) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) @@ -483,11 +488,11 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 1) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, qs) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, qs) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) @@ -499,10 +504,10 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) @@ -522,20 +527,24 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) - textTwoId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textTwoId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleantwoid, }) require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textTwoId, + }) + require.NoError(t, err) _, err = queries.AddResult(ctx, &repository.AddResultParams{ Queryid: contextQueryID, @@ -545,13 +554,13 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 1) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, qs) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, qs) _, err = queries.AddResult(ctx, &repository.AddResultParams{ Queryid: jsonQueryID, @@ -561,10 +570,10 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 0) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 0) @@ -576,12 +585,12 @@ func TestUnsyncedNoDepsQueries(t *testing.T) { }) require.NoError(t, err) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentID) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentID) require.NoError(t, err) assert.Len(t, qs, 1) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, qs) - qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, documentTwoID) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, qs) + qs, err = queries.ListUnsyncedNoDepsQueriesByDocId(ctx, &documentTwoID) require.NoError(t, err) assert.Len(t, qs, 1) - assert.ElementsMatch(t, []pgtype.UUID{jsonQueryID}, qs) + assert.ElementsMatch(t, []*uuid.UUID{&jsonQueryID}, qs) } diff --git a/internal/database/repository/sync_test.go b/internal/database/repository/sync_test.go index 8506bdad..59915425 100644 --- a/internal/database/repository/sync_test.go +++ b/internal/database/repository/sync_test.go @@ -2,8 +2,6 @@ package repository_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" @@ -22,7 +20,6 @@ func TestListClientDocumentIDs(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -61,7 +58,7 @@ func TestListClientDocumentIDs(t *testing.T) { total := int64(1) assert.ElementsMatch(t, []*repository.ListDocumentIDsBatchRow{ { - ID: docOne, + ID: &docOne, Totalcount: &total, }, }, ids) @@ -82,7 +79,7 @@ func TestListClientDocumentIDs(t *testing.T) { total = int64(2) assert.ElementsMatch(t, []*repository.ListDocumentIDsBatchRow{ { - ID: docOne, + ID: &docOne, Totalcount: &total, }, }, ids) @@ -96,7 +93,7 @@ func TestListClientDocumentIDs(t *testing.T) { assert.Len(t, ids, 1) assert.ElementsMatch(t, []*repository.ListDocumentIDsBatchRow{ { - ID: docTwo, + ID: &docTwo, Totalcount: &total, }, }, ids) @@ -110,11 +107,11 @@ func TestListClientDocumentIDs(t *testing.T) { assert.Len(t, ids, 2) assert.ElementsMatch(t, []*repository.ListDocumentIDsBatchRow{ { - ID: docOne, + ID: &docOne, Totalcount: &total, }, { - ID: docTwo, + ID: &docTwo, Totalcount: &total, }, }, ids) @@ -128,7 +125,6 @@ func TestClientSync(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -184,7 +180,7 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err := queries.IsClientSynced(ctx, clientId) + isSynced, err := queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) @@ -197,7 +193,7 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - docExternal, err := queries.GetDocumentExternal(ctx, documentID) + docExternal, err := queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -206,7 +202,7 @@ func TestClientSync(t *testing.T) { Fields: []byte(`{"first_key": null}`), }, docExternal) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) @@ -224,10 +220,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -244,11 +240,11 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err := queries.GetDocumentExternal(ctx, documentID) + docExternal, err := queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -274,10 +270,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -286,18 +282,23 @@ func TestClientSync(t *testing.T) { Fields: []byte(`{"first_key": null}`), }, docExternal) - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanId, + Hash: "example", + }) + require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -315,10 +316,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -335,10 +336,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -353,11 +354,11 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -375,10 +376,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -396,10 +397,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -416,10 +417,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -434,10 +435,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -448,18 +449,22 @@ func TestClientSync(t *testing.T) { }) t.Run("update text entry", func(t *testing.T) { - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanId, }) require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, + }) + require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -476,10 +481,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -496,10 +501,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -514,10 +519,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -543,10 +548,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -555,18 +560,22 @@ func TestClientSync(t *testing.T) { Fields: []byte(`{"first_key": null}`), }, docExternal) - textThreeId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textThreeId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: "hi", Key: "hello", Cleanentryid: cleanthreeid, }) require.NoError(t, err) + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textThreeId, + }) + require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -583,10 +592,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -603,10 +612,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -621,10 +630,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -636,10 +645,10 @@ func TestClientSync(t *testing.T) { latestCollectorVersion, err := queries.AddLatestCollectorVersion(ctx, clientId) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -655,10 +664,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -674,10 +683,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -694,10 +703,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -716,10 +725,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -754,10 +763,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -774,10 +783,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -794,10 +803,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -812,10 +821,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.False(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, @@ -830,10 +839,10 @@ func TestClientSync(t *testing.T) { }) require.NoError(t, err) - isSynced, err = queries.IsClientSynced(ctx, clientId) + isSynced, err = queries.IsClientSynced(ctx, &clientId) require.NoError(t, err) assert.True(t, isSynced) - docExternal, err = queries.GetDocumentExternal(ctx, documentID) + docExternal, err = queries.GetDocumentExternal(ctx, &documentID) require.NoError(t, err) assert.EqualExportedValues(t, &repository.GetDocumentExternalRow{ ID: documentID, diff --git a/internal/database/repository/text.sql.go b/internal/database/repository/text.sql.go index 295b9c1a..4a877d43 100644 --- a/internal/database/repository/text.sql.go +++ b/internal/database/repository/text.sql.go @@ -8,47 +8,95 @@ package repository import ( "context" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" ) -const addDocumentTextEntry = `-- name: AddDocumentTextEntry :one -INSERT INTO documentTextExtractions (version, bucket, key, cleanEntryId) VALUES ($1, $2, $3, $4) returning id +const addDocumentText = `-- name: AddDocumentText :one +INSERT INTO documentTextExtractions (bucket, key, cleanEntryId, hash) VALUES ($1, $2, $3, $4) returning id ` -type AddDocumentTextEntryParams struct { - Version int64 `db:"version"` - Bucket string `db:"bucket"` - Key string `db:"key"` - Cleanentryid pgtype.UUID `db:"cleanentryid"` +type AddDocumentTextParams struct { + Bucket string `db:"bucket"` + Key string `db:"key"` + Cleanentryid uuid.UUID `db:"cleanentryid"` + Hash string `db:"hash"` } -// AddDocumentTextEntry +// AddDocumentText // -// INSERT INTO documentTextExtractions (version, bucket, key, cleanEntryId) VALUES ($1, $2, $3, $4) returning id -func (q *Queries) AddDocumentTextEntry(ctx context.Context, arg *AddDocumentTextEntryParams) (pgtype.UUID, error) { - row := q.db.QueryRow(ctx, addDocumentTextEntry, - arg.Version, +// INSERT INTO documentTextExtractions (bucket, key, cleanEntryId, hash) VALUES ($1, $2, $3, $4) returning id +func (q *Queries) AddDocumentText(ctx context.Context, arg *AddDocumentTextParams) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, addDocumentText, arg.Bucket, arg.Key, arg.Cleanentryid, + arg.Hash, ) - var id pgtype.UUID + var id uuid.UUID err := row.Scan(&id) return id, err } +const addDocumentTextEntry = `-- name: AddDocumentTextEntry :exec +INSERT INTO documentTextExtractionEntries (textId, version) VALUES ($1, $2) +` + +type AddDocumentTextEntryParams struct { + Textid uuid.UUID `db:"textid"` + Version int64 `db:"version"` +} + +// AddDocumentTextEntry +// +// INSERT INTO documentTextExtractionEntries (textId, version) VALUES ($1, $2) +func (q *Queries) AddDocumentTextEntry(ctx context.Context, arg *AddDocumentTextEntryParams) error { + _, err := q.db.Exec(ctx, addDocumentTextEntry, arg.Textid, arg.Version) + return err +} + +const getDocumentTextExtractionByHash = `-- name: GetDocumentTextExtractionByHash :one +SELECT id, documentId, bucket, key, version, hash, cleanEntryId + FROM currentTextEntries + WHERE cleanEntryId = $1 and hash = $2 +` + +type GetDocumentTextExtractionByHashParams struct { + Cleanentryid uuid.UUID `db:"cleanentryid"` + Hash string `db:"hash"` +} + +// GetDocumentTextExtractionByHash +// +// SELECT id, documentId, bucket, key, version, hash, cleanEntryId +// FROM currentTextEntries +// WHERE cleanEntryId = $1 and hash = $2 +func (q *Queries) GetDocumentTextExtractionByHash(ctx context.Context, arg *GetDocumentTextExtractionByHashParams) (*Currenttextentry, error) { + row := q.db.QueryRow(ctx, getDocumentTextExtractionByHash, arg.Cleanentryid, arg.Hash) + var i Currenttextentry + err := row.Scan( + &i.ID, + &i.Documentid, + &i.Bucket, + &i.Key, + &i.Version, + &i.Hash, + &i.Cleanentryid, + ) + return &i, err +} + const getTextEntryByDocId = `-- name: GetTextEntryByDocId :one -SELECT id, documentId, bucket, key, version, cleanEntryId +SELECT id, documentId, bucket, key, version, hash, cleanEntryId FROM currentTextEntries WHERE documentId = $1 ` // GetTextEntryByDocId // -// SELECT id, documentId, bucket, key, version, cleanEntryId +// SELECT id, documentId, bucket, key, version, hash, cleanEntryId // FROM currentTextEntries // WHERE documentId = $1 -func (q *Queries) GetTextEntryByDocId(ctx context.Context, documentid pgtype.UUID) (*Currenttextentry, error) { +func (q *Queries) GetTextEntryByDocId(ctx context.Context, documentid uuid.UUID) (*Currenttextentry, error) { row := q.db.QueryRow(ctx, getTextEntryByDocId, documentid) var i Currenttextentry err := row.Scan( @@ -57,6 +105,7 @@ func (q *Queries) GetTextEntryByDocId(ctx context.Context, documentid pgtype.UUI &i.Bucket, &i.Key, &i.Version, + &i.Hash, &i.Cleanentryid, ) return &i, err @@ -73,7 +122,7 @@ SELECT EXISTS( // SELECT EXISTS( // SELECT 1 FROM currentTextEntries WHERE documentId = $1 // ) -func (q *Queries) IsDocumentTextExtracted(ctx context.Context, documentid pgtype.UUID) (bool, error) { +func (q *Queries) IsDocumentTextExtracted(ctx context.Context, documentid uuid.UUID) (bool, error) { row := q.db.QueryRow(ctx, isDocumentTextExtracted, documentid) var exists bool err := row.Scan(&exists) diff --git a/internal/database/repository/text_test.go b/internal/database/repository/text_test.go index 0ead79f3..76a65f2f 100644 --- a/internal/database/repository/text_test.go +++ b/internal/database/repository/text_test.go @@ -2,15 +2,13 @@ package repository_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/test" - "github.com/jackc/pgx/v5/pgtype" + "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +21,6 @@ func TestTextExtraction(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, textup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, @@ -68,15 +65,25 @@ func TestTextExtraction(t *testing.T) { require.NoError(t, err) assert.False(t, isextract) - textId, err := queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: 1, + textId, err := queries.AddDocumentText(ctx, &repository.AddDocumentTextParams{ Bucket: bucket, Key: key, Cleanentryid: cleanid, + Hash: "example", }) require.NoError(t, err) assert.NotNil(t, textId) - assert.NotEqual(t, pgtype.UUID{}, textId) + assert.NotEqual(t, uuid.UUID{}, textId) + + isextract, err = queries.IsDocumentTextExtracted(ctx, id) + require.NoError(t, err) + assert.False(t, isextract) + + err = queries.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: 1, + Textid: textId, + }) + require.NoError(t, err) isextract, err = queries.IsDocumentTextExtracted(ctx, id) require.NoError(t, err) @@ -89,4 +96,17 @@ func TestTextExtraction(t *testing.T) { assert.Equal(t, key, text.Key) assert.Equal(t, int64(1), text.Version) assert.Equal(t, textId, text.ID) + + uniqueEntry, err := queries.GetDocumentTextExtractionByHash(ctx, &repository.GetDocumentTextExtractionByHashParams{ + Hash: "example", + Cleanentryid: cleanid, + }) + require.NoError(t, err) + assert.EqualExportedValues(t, text, uniqueEntry) + + _, err = queries.GetDocumentTextExtractionByHash(ctx, &repository.GetDocumentTextExtractionByHashParams{ + Hash: "definitely invalid", + Cleanentryid: cleanid, + }) + require.EqualError(t, err, "no rows in result set") } diff --git a/internal/document/clean/clean.go b/internal/document/clean/clean.go index c84afe47..e3642bd3 100644 --- a/internal/document/clean/clean.go +++ b/internal/document/clean/clean.go @@ -7,7 +7,6 @@ import ( "fmt" "log/slog" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig/build" @@ -88,7 +87,7 @@ func (s *Service) executeCleanTasks(ctx context.Context, params *CleanParams) (* func (s *Service) clean(ctx context.Context, id uuid.UUID) error { slog.Debug("cleaning document", "id", id.String()) - docId := database.MustToDBUUID(id) + docId := id doc, err := s.cfg.GetDBQueries().GetDocumentSummary(ctx, docId) if err != nil { @@ -121,7 +120,7 @@ func (s *Service) clean(ctx context.Context, id uuid.UUID) error { } func (s *Service) storeClean(ctx context.Context, id uuid.UUID, out *ExecuteCleanResponse) error { - docId := database.MustToDBUUID(id) + docId := id version := build.GetVersionUnixTimestamp() params := &repository.AddDocumentCleanParams{ @@ -174,7 +173,7 @@ func (s *Service) storeClean(ctx context.Context, id uuid.UUID, out *ExecuteClea } func (s *Service) isNewClean(lastEntry *repository.GetMostRecentDocumentCleanEntryRow, out *ExecuteCleanResponse) bool { - if lastEntry == nil || !lastEntry.ID.Valid { + if lastEntry == nil { return true } @@ -186,6 +185,10 @@ func (s *Service) isNewClean(lastEntry *repository.GetMostRecentDocumentCleanEnt return true } + if out.location == nil || out.mimetype == nil || lastEntry.Bucket == nil || lastEntry.Key == nil { + return true + } + return !(out.location.Bucket == *lastEntry.Bucket && out.location.Key == *lastEntry.Key && *out.mimetype == ParseDBNullMimeType(lastEntry.Mimetype)) diff --git a/internal/document/clean/clean_test.go b/internal/document/clean/clean_test.go index d8ee7629..f0e3d0b4 100644 --- a/internal/document/clean/clean_test.go +++ b/internal/document/clean/clean_test.go @@ -6,7 +6,6 @@ import ( "strings" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" objectstoremock "queryorchestration/mocks/objectstore" @@ -44,12 +43,12 @@ func TestClean(t *testing.T) { Bucket: "bucket_name", Key: "/i/am/here", } - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(dbid). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(dbid, database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(dbid, doc.ClientID, doc.Hash), ) pool.ExpectQuery("name: GetDocumentEntry :one").WithArgs(dbid).WillReturnRows( pgxmock.NewRows([]string{"documentId", "bucket", "key"}). @@ -65,7 +64,7 @@ func TestClean(t *testing.T) { WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}), ) - cleanid := database.MustToDBUUID(uuid.New()) + cleanid := uuid.New() pool.ExpectQuery("name: AddDocumentClean :one").WithArgs(dbid, &inloc.Bucket, &inloc.Key, dbmimetype, repository.NullCleanfailtype{}). WillReturnRows( pgxmock.NewRows([]string{"id"}). @@ -186,7 +185,7 @@ func TestStoreClean(t *testing.T) { location: &inloc, mimetype: (*MimeType)(&mimeType), } - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID dbmimetype := repository.NullCleanmimetype{ Valid: true, @@ -197,7 +196,7 @@ func TestStoreClean(t *testing.T) { WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}), ) - cleanid := database.MustToDBUUID(uuid.New()) + cleanid := uuid.New() pool.ExpectQuery("name: AddDocumentClean :one").WithArgs(dbid, &inloc.Bucket, &inloc.Key, dbmimetype, repository.NullCleanfailtype{}). WillReturnRows( pgxmock.NewRows([]string{"id"}). @@ -216,7 +215,7 @@ func TestStoreClean(t *testing.T) { location: &inloc, mimetype: (*MimeType)(&mimeType), } - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID dbmimetype := repository.NullCleanmimetype{ Valid: true, @@ -226,9 +225,9 @@ func TestStoreClean(t *testing.T) { pool.ExpectQuery("name: GetMostRecentDocumentCleanEntry :one").WithArgs(dbid). WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(database.MustToDBUUID(uuid.New()), dbid, nil, nil, int64(1), nil, repository.CleanfailtypeInvalidRead), + AddRow(uuid.New(), dbid, nil, nil, int64(1), nil, repository.CleanfailtypeInvalidRead), ) - cleanid := database.MustToDBUUID(uuid.New()) + cleanid := uuid.New() pool.ExpectQuery("name: AddDocumentClean :one").WithArgs(dbid, &inloc.Bucket, &inloc.Key, dbmimetype, repository.NullCleanfailtype{}). WillReturnRows( pgxmock.NewRows([]string{"id"}). @@ -246,8 +245,8 @@ func TestStoreClean(t *testing.T) { params := &ExecuteCleanResponse{ failReason: &reason, } - dbid := database.MustToDBUUID(doc.ID) - cleanid := database.MustToDBUUID(uuid.New()) + dbid := doc.ID + cleanid := uuid.New() pool.ExpectBegin() pool.ExpectQuery("name: GetMostRecentDocumentCleanEntry :one").WithArgs(dbid). @@ -276,7 +275,7 @@ func TestIsNewClean(t *testing.T) { }) t.Run("same fail", func(t *testing.T) { var lastEntry *repository.GetMostRecentDocumentCleanEntryRow = &repository.GetMostRecentDocumentCleanEntryRow{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Fail: repository.NullCleanfailtype{ Valid: true, Cleanfailtype: repository.CleanfailtypeInvalidMimetype, @@ -290,7 +289,7 @@ func TestIsNewClean(t *testing.T) { }) t.Run("different fail", func(t *testing.T) { var lastEntry *repository.GetMostRecentDocumentCleanEntryRow = &repository.GetMostRecentDocumentCleanEntryRow{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Fail: repository.NullCleanfailtype{ Valid: true, Cleanfailtype: repository.CleanfailtypeInvalidMimetype, @@ -309,7 +308,7 @@ func TestIsNewClean(t *testing.T) { } mimeType := MimeTypePDF var lastEntry *repository.GetMostRecentDocumentCleanEntryRow = &repository.GetMostRecentDocumentCleanEntryRow{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Bucket: &loc.Bucket, Key: &loc.Key, Mimetype: repository.NullCleanmimetype{ @@ -334,7 +333,7 @@ func TestIsNewClean(t *testing.T) { } mimeType := MimeTypePDF var lastEntry *repository.GetMostRecentDocumentCleanEntryRow = &repository.GetMostRecentDocumentCleanEntryRow{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Bucket: &ogloc.Bucket, Key: &ogloc.Key, Mimetype: repository.NullCleanmimetype{ diff --git a/internal/document/clean/create.go b/internal/document/clean/create.go index 69b9aba3..c5b01133 100644 --- a/internal/document/clean/create.go +++ b/internal/document/clean/create.go @@ -4,14 +4,13 @@ import ( "context" doctextrunner "queryorchestration/api/docTextRunner" - "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig/queue" "github.com/google/uuid" ) func (s *Service) Clean(ctx context.Context, id uuid.UUID) error { - isclean, err := s.cfg.GetDBQueries().HasDocumentCleanEntry(ctx, database.MustToDBUUID(id)) + isclean, err := s.cfg.GetDBQueries().HasDocumentCleanEntry(ctx, id) if err != nil { return err } diff --git a/internal/document/clean/create_test.go b/internal/document/clean/create_test.go index 2b68efd5..a0b2eae3 100644 --- a/internal/document/clean/create_test.go +++ b/internal/document/clean/create_test.go @@ -7,7 +7,6 @@ import ( "strings" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" @@ -58,7 +57,7 @@ func TestCreate(t *testing.T) { Bucket: "bucket_name", Key: "/i/am/here", } - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID pool.ExpectQuery("name: HasDocumentCleanEntry :one").WithArgs(dbid).WillReturnRows( pgxmock.NewRows([]string{"isclean"}). @@ -67,7 +66,7 @@ func TestCreate(t *testing.T) { pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(dbid). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(dbid, database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(dbid, doc.ClientID, doc.Hash), ) pool.ExpectQuery("name: GetDocumentEntry :one").WithArgs(dbid).WillReturnRows( pgxmock.NewRows([]string{"documentId", "bucket", "key"}). @@ -83,7 +82,7 @@ func TestCreate(t *testing.T) { WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}), ) - cleanid := database.MustToDBUUID(uuid.New()) + cleanid := uuid.New() pool.ExpectQuery("name: AddDocumentClean :one").WithArgs(dbid, &inloc.Bucket, &inloc.Key, dbmimetype, repository.NullCleanfailtype{}). WillReturnRows( pgxmock.NewRows([]string{"id"}). diff --git a/internal/document/get.go b/internal/document/get.go index 05deff9e..40d0fe99 100644 --- a/internal/document/get.go +++ b/internal/document/get.go @@ -4,26 +4,24 @@ import ( "context" "encoding/json" - "queryorchestration/internal/database" - "github.com/google/uuid" ) func (s *Service) GetSummary(ctx context.Context, id uuid.UUID) (*DocumentSummary, error) { - doc, err := s.cfg.GetDBQueries().GetDocumentSummary(ctx, database.MustToDBUUID(id)) + doc, err := s.cfg.GetDBQueries().GetDocumentSummary(ctx, id) if err != nil { return nil, err } return &DocumentSummary{ - ID: database.MustToUUID(doc.ID), - ClientID: database.MustToUUID(doc.Clientid), + ID: doc.ID, + ClientID: doc.Clientid, Hash: doc.Hash, }, nil } func (s *Service) GetExternal(ctx context.Context, id uuid.UUID) (*DocumentExternal, error) { - doc, err := s.cfg.GetDBQueries().GetDocumentExternal(ctx, database.MustToDBUUID(id)) + doc, err := s.cfg.GetDBQueries().GetDocumentExternal(ctx, &id) if err != nil { return nil, err } @@ -35,7 +33,7 @@ func (s *Service) GetExternal(ctx context.Context, id uuid.UUID) (*DocumentExter } return &DocumentExternal{ - Id: database.MustToUUID(doc.ID), + Id: doc.ID, ClientID: doc.Clientid, Hash: doc.Hash, Fields: fields, diff --git a/internal/document/get_test.go b/internal/document/get_test.go index 3c737c4d..cb51b0d2 100644 --- a/internal/document/get_test.go +++ b/internal/document/get_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" @@ -33,10 +32,10 @@ func TestGetSummary(t *testing.T) { Hash: "example_hash", } - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(doc.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(doc.ID), database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(doc.ID, doc.ClientID, doc.Hash), ) adoc, err := svc.GetSummary(ctx, doc.ID) @@ -64,10 +63,10 @@ func TestGetExternal(t *testing.T) { }, } - pool.ExpectQuery("name: GetDocumentExternal :one").WithArgs(database.MustToDBUUID(doc.Id)). + pool.ExpectQuery("name: GetDocumentExternal :one").WithArgs(&doc.Id). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash", "fields"}). - AddRow(database.MustToDBUUID(doc.Id), "externalID", "example", []byte(`{"json": "hello"}`)), + AddRow(doc.Id, "externalID", "example", []byte(`{"json": "hello"}`)), ) adoc, err := svc.GetExternal(ctx, doc.Id) diff --git a/internal/document/init/create.go b/internal/document/init/create.go index f80c9f37..c963515a 100644 --- a/internal/document/init/create.go +++ b/internal/document/init/create.go @@ -9,13 +9,11 @@ import ( "regexp" docsyncrunner "queryorchestration/api/docSyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig/queue" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" ) type Create struct { @@ -52,18 +50,18 @@ func (s *Service) Create(ctx context.Context, doc *Create) (uuid.UUID, error) { } type createDocumentParams struct { - ID *pgtype.UUID - ClientID pgtype.UUID + ID *uuid.UUID + ClientID uuid.UUID Hash string Location document.Location } func (s *Service) getCreateParams(ctx context.Context, doc *Create) (*createDocumentParams, error) { idbyhash, err := s.cfg.GetDBQueries().GetDocumentIDByHash(ctx, &repository.GetDocumentIDByHashParams{ - Clientid: database.MustToDBUUID(doc.ClientID), + Clientid: doc.ClientID, Hash: doc.Hash, }) - var docID *pgtype.UUID + var docID *uuid.UUID if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } else if err == nil { @@ -72,7 +70,7 @@ func (s *Service) getCreateParams(ctx context.Context, doc *Create) (*createDocu return &createDocumentParams{ ID: docID, - ClientID: database.MustToDBUUID(doc.ClientID), + ClientID: doc.ClientID, Hash: doc.Hash, Location: doc.Location, }, nil @@ -82,7 +80,7 @@ func (s *Service) submitCreate(ctx context.Context, params *createDocumentParams var id uuid.UUID err := s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { - var dbid pgtype.UUID + var dbid uuid.UUID if params.ID == nil { createid, err := s.cfg.GetDBQueries().CreateDocument(ctx, &repository.CreateDocumentParams{ Clientid: params.ClientID, @@ -109,7 +107,7 @@ func (s *Service) submitCreate(ctx context.Context, params *createDocumentParams return err } - id = database.MustToUUID(dbid) + id = dbid return nil }) diff --git a/internal/document/init/create_test.go b/internal/document/init/create_test.go index 02d4175a..d927eb8b 100644 --- a/internal/document/init/create_test.go +++ b/internal/document/init/create_test.go @@ -6,7 +6,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" queuemock "queryorchestration/mocks/queue" @@ -45,30 +44,30 @@ func TestCreate(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, database.MustToDBUUID(doc.ClientID)).WillReturnRows( + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, doc.ClientID).WillReturnRows( pgxmock.NewRows([]string{"id"}), ) pool.ExpectBegin() - pool.ExpectQuery("name: CreateDocument :one").WithArgs(database.MustToDBUUID(doc.ClientID), doc.Hash). + pool.ExpectQuery("name: CreateDocument :one").WithArgs(doc.ClientID, doc.Hash). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(doc.ID)), + AddRow(doc.ID), ) - pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(database.MustToDBUUID(doc.ID), location.Bucket, location.Key). + pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(doc.ID, location.Bucket, location.Key). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(doc.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(doc.ID), database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(doc.ID, doc.ClientID, doc.Hash), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: GetClient :one").WithArgs(clientId).WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "canSync"}). - AddRow(database.MustToDBUUID(clientId), database.MustToDBUUID(clientId), true), + AddRow(clientId, clientId, true), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(clientId)).WillReturnRows( + pool.ExpectQuery("name: GetClient :one").WithArgs(clientId).WillReturnRows( pgxmock.NewRows([]string{"id", "name", "canSync"}). - AddRow(database.MustToDBUUID(clientId), "client_name", true), + AddRow(clientId, "client_name", true), ) mockSQS.EXPECT(). @@ -110,7 +109,7 @@ func TestGetCreateParams(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, database.MustToDBUUID(doc.ClientID)).WillReturnRows( + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, doc.ClientID).WillReturnRows( pgxmock.NewRows([]string{"id"}), ) @@ -121,7 +120,7 @@ func TestGetCreateParams(t *testing.T) { }) require.NoError(t, err) assert.Equal(t, &createDocumentParams{ - ClientID: database.MustToDBUUID(doc.ClientID), + ClientID: doc.ClientID, Hash: doc.Hash, Location: location, }, params) @@ -148,9 +147,9 @@ func TestGetCreateParamsExisting(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, database.MustToDBUUID(doc.ClientID)).WillReturnRows( + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, doc.ClientID).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(doc.ID)), + AddRow(doc.ID), ) params, err := svc.getCreateParams(ctx, &Create{ @@ -159,10 +158,10 @@ func TestGetCreateParamsExisting(t *testing.T) { Hash: doc.Hash, }) require.NoError(t, err) - dbid := database.MustToDBUUID(doc.ID) + dbid := doc.ID assert.Equal(t, &createDocumentParams{ ID: &dbid, - ClientID: database.MustToDBUUID(doc.ClientID), + ClientID: doc.ClientID, Hash: doc.Hash, Location: location, }, params) @@ -188,7 +187,7 @@ func TestGetCreateParamsCurrentDocErr(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, database.MustToDBUUID(doc.ClientID)). + pool.ExpectQuery("name: GetDocumentIDByHash :one").WithArgs(doc.Hash, doc.ClientID). WillReturnError(errors.New("db err")) _, err = svc.getCreateParams(ctx, &Create{ @@ -220,17 +219,17 @@ func TestSubmitCreate(t *testing.T) { } pool.ExpectBegin() - pool.ExpectQuery("name: CreateDocument :one").WithArgs(database.MustToDBUUID(doc.ClientID), doc.Hash). + pool.ExpectQuery("name: CreateDocument :one").WithArgs(doc.ClientID, doc.Hash). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(doc.ID)), + AddRow(doc.ID), ) - pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(database.MustToDBUUID(doc.ID), location.Bucket, location.Key). + pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(doc.ID, location.Bucket, location.Key). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() id, err := svc.submitCreate(ctx, &createDocumentParams{ - ClientID: database.MustToDBUUID(doc.ClientID), + ClientID: doc.ClientID, Location: location, Hash: doc.Hash, }) @@ -260,14 +259,14 @@ func TestSubmitCreateExists(t *testing.T) { } pool.ExpectBegin() - pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(database.MustToDBUUID(doc.ID), location.Bucket, location.Key). + pool.ExpectExec("name: AddDocumentEntry :exec").WithArgs(doc.ID, location.Bucket, location.Key). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - docid := database.MustToDBUUID(doc.ID) + docid := doc.ID id, err := svc.submitCreate(ctx, &createDocumentParams{ ID: &docid, - ClientID: database.MustToDBUUID(doc.ClientID), + ClientID: doc.ClientID, Location: location, Hash: doc.Hash, }) diff --git a/internal/document/list.go b/internal/document/list.go index 18969b73..cb559c4d 100644 --- a/internal/document/list.go +++ b/internal/document/list.go @@ -2,8 +2,6 @@ package document import ( "context" - - "queryorchestration/internal/database" ) func (s *Service) ListByClientExternalId(ctx context.Context, id string) ([]*DocumentSummary, error) { @@ -15,7 +13,7 @@ func (s *Service) ListByClientExternalId(ctx context.Context, id string) ([]*Doc docs := make([]*DocumentSummary, len(documents)) for i, doc := range documents { docs[i] = &DocumentSummary{ - ID: database.MustToUUID(doc.ID), + ID: doc.ID, Hash: doc.Hash, } } diff --git a/internal/document/list_test.go b/internal/document/list_test.go index 41f90cd1..f7dacc7e 100644 --- a/internal/document/list_test.go +++ b/internal/document/list_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" @@ -37,7 +36,7 @@ func TestListByClientId(t *testing.T) { pool.ExpectQuery("name: ListDocumentsByClientExternalId :many").WithArgs(clientId). WillReturnRows( pgxmock.NewRows([]string{"id", "hash"}). - AddRow(database.MustToDBUUID(doc[0].ID), doc[0].Hash), + AddRow(doc[0].ID, doc[0].Hash), ) adoc, err := svc.ListByClientExternalId(ctx, clientId) diff --git a/internal/document/sync/sync_test.go b/internal/document/sync/sync_test.go index 77597d57..4d09ac8c 100644 --- a/internal/document/sync/sync_test.go +++ b/internal/document/sync/sync_test.go @@ -6,7 +6,6 @@ import ( "testing" "queryorchestration/internal/client" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" documentsync "queryorchestration/internal/document/sync" @@ -47,14 +46,14 @@ func TestSync(t *testing.T) { Hash: "example_hash", } - pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(database.MustToDBUUID(doc.ID)). + pool.ExpectQuery("name: GetDocumentSummary :one").WithArgs(doc.ID). WillReturnRows( pgxmock.NewRows([]string{"id", "clientId", "hash"}). - AddRow(database.MustToDBUUID(doc.ID), database.MustToDBUUID(doc.ClientID), doc.Hash), + AddRow(doc.ID, doc.ClientID, doc.Hash), ) - pool.ExpectQuery("name: GetClient :one").WithArgs(database.MustToDBUUID(j.ID)).WillReturnRows( + pool.ExpectQuery("name: GetClient :one").WithArgs(j.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "externalId", "name", "canSync"}). - AddRow(database.MustToDBUUID(j.ID), "id", "client_name", true), + AddRow(j.ID, "id", "client_name", true), ) mockSQS.EXPECT(). diff --git a/internal/document/text/create.go b/internal/document/text/create.go index 457a2583..0354ebb3 100644 --- a/internal/document/text/create.go +++ b/internal/document/text/create.go @@ -5,7 +5,6 @@ import ( "log/slog" querysyncrunner "queryorchestration/api/querySyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig/queue" "github.com/google/uuid" @@ -14,13 +13,13 @@ import ( func (s *Service) Extract(ctx context.Context, id uuid.UUID) error { slog.Debug("extracting document text", "id", id.String()) - isextracted, err := s.cfg.GetDBQueries().IsDocumentTextExtracted(ctx, database.MustToDBUUID(id)) + isextracted, err := s.cfg.GetDBQueries().IsDocumentTextExtracted(ctx, id) if err != nil { return err } if !isextracted { - entry, err := s.cfg.GetDBQueries().GetCleanEntryByDocId(ctx, database.MustToDBUUID(id)) + entry, err := s.cfg.GetDBQueries().GetCleanEntryByDocId(ctx, id) if err != nil { return err } else if entry.Fail.Valid { @@ -28,7 +27,7 @@ func (s *Service) Extract(ctx context.Context, id uuid.UUID) error { return nil } - err = s.extract(ctx, database.MustToUUID(entry.ID)) + err = s.extract(ctx, entry.ID) if err != nil { return err } diff --git a/internal/document/text/create_test.go b/internal/document/text/create_test.go index 5ed0890d..b687c549 100644 --- a/internal/document/text/create_test.go +++ b/internal/document/text/create_test.go @@ -5,11 +5,11 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/querysync" + "queryorchestration/internal/serviceconfig/textract" queuemock "queryorchestration/mocks/queue" "github.com/stretchr/testify/require" @@ -23,6 +23,7 @@ import ( type DocTextConfig struct { serviceconfig.BaseConfig querysync.QuerySyncConfig + textract.TextractConfig } func TestCreate(t *testing.T) { @@ -49,29 +50,37 @@ func TestCreate(t *testing.T) { Key: "/i/am/here", } - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"isextracted"}). AddRow(false), ) - cleanId := database.MustToDBUUID(uuid.New()) + cleanId := uuid.New() mimeType := "application/pdf" dbmimetype := repository.NullCleanmimetype{ Valid: true, Cleanmimetype: repository.Cleanmimetype(mimeType), } - pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(cleanId, database.MustToDBUUID(id), &inloc.Bucket, &inloc.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(cleanId, id, &inloc.Bucket, &inloc.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), ) pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(cleanId).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(cleanId, database.MustToDBUUID(id), &inloc.Bucket, &inloc.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(cleanId, id, &inloc.Bucket, &inloc.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), ) - pool.ExpectQuery("name: AddDocumentTextEntry :one").WithArgs(pgxmock.AnyArg(), inloc.Bucket, inloc.Key, cleanId). + textId := uuid.New() + pool.ExpectBegin() + pool.ExpectQuery("name: GetDocumentTextExtractionByHash :one").WithArgs(cleanId, "example").WillReturnRows( + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}), + ) + pool.ExpectQuery("name: AddDocumentText :one").WithArgs(inloc.Bucket, inloc.Key, cleanId, "example"). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(uuid.New())), + AddRow(textId), ) + pool.ExpectExec("name: AddDocumentTextEntry :exec").WithArgs(textId, pgxmock.AnyArg()). + WillReturnResult(pgxmock.NewResult("", 1)) + pool.ExpectCommit() mockSQS.EXPECT(). SendMessage( @@ -93,12 +102,12 @@ func TestCreate(t *testing.T) { Cleanfailtype: repository.CleanfailtypeInvalidMimetype, } - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"isextracted"}).AddRow(false), ) - pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetCleanEntryByDocId :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(database.MustToDBUUID(id), database.MustToDBUUID(uuid.New()), nil, nil, int64(1), nil, fail), + AddRow(id, uuid.New(), nil, nil, int64(1), nil, fail), ) err = svc.Extract(ctx, id) diff --git a/internal/document/text/extract.go b/internal/document/text/extract.go index 724ace95..d0e00d73 100644 --- a/internal/document/text/extract.go +++ b/internal/document/text/extract.go @@ -2,9 +2,10 @@ package documenttext import ( "context" + "database/sql" + "errors" "fmt" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/serviceconfig/build" @@ -12,37 +13,86 @@ import ( "github.com/google/uuid" ) -func (s *Service) executeExtraction(ctx context.Context, cleanId uuid.UUID) (*document.Location, error) { - entry, err := s.cfg.GetDBQueries().GetCleanEntry(ctx, database.MustToDBUUID(cleanId)) +type extraction struct { + TextLocation document.Location + Hash string +} + +func (s *Service) executeExtraction(ctx context.Context, cleanId uuid.UUID) (*extraction, error) { + entry, err := s.cfg.GetDBQueries().GetCleanEntry(ctx, cleanId) if err != nil { return nil, err } else if entry.Fail.Valid { return nil, fmt.Errorf("no valid cleaning") } - return &document.Location{ - Bucket: *entry.Bucket, - Key: *entry.Key, + // analysis, detection - diff? + // split page by page? + // output format + // index + // pages + // block types + + return &extraction{ + Hash: "example", + TextLocation: document.Location{ + Bucket: *entry.Bucket, + Key: *entry.Key, + }, }, nil } func (s *Service) extract(ctx context.Context, cleanId uuid.UUID) error { - outLocation, err := s.executeExtraction(ctx, cleanId) + details, err := s.executeExtraction(ctx, cleanId) if err != nil { return err } - version := build.GetVersionUnixTimestamp() - - _, err = s.cfg.GetDBQueries().AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ - Version: version, - Bucket: outLocation.Bucket, - Key: outLocation.Key, - Cleanentryid: database.MustToDBUUID(cleanId), - }) + err = s.storeExtraction(ctx, cleanId, details) if err != nil { return err } return nil } + +func (s *Service) storeExtraction(ctx context.Context, cleanId uuid.UUID, details *extraction) error { + version := build.GetVersionUnixTimestamp() + + return s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { + existing, err := q.GetDocumentTextExtractionByHash(ctx, &repository.GetDocumentTextExtractionByHashParams{ + Hash: details.Hash, + Cleanentryid: cleanId, + }) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + + var textId uuid.UUID + if existing == nil || errors.Is(err, sql.ErrNoRows) { + newTextId, err := q.AddDocumentText(ctx, &repository.AddDocumentTextParams{ + Bucket: details.TextLocation.Bucket, + Key: details.TextLocation.Key, + Cleanentryid: cleanId, + Hash: details.Hash, + }) + if err != nil { + return err + } + + textId = newTextId + } else { + textId = existing.ID + } + + err = q.AddDocumentTextEntry(ctx, &repository.AddDocumentTextEntryParams{ + Version: version, + Textid: textId, + }) + if err != nil { + return err + } + + return nil + }) +} diff --git a/internal/document/text/extract_test.go b/internal/document/text/extract_test.go index 444a209e..a17aa50b 100644 --- a/internal/document/text/extract_test.go +++ b/internal/document/text/extract_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" @@ -36,7 +35,7 @@ func TestExtract(t *testing.T) { } cleanId := uuid.New() - dbCleanId := database.MustToDBUUID(cleanId) + dbCleanId := cleanId mimeType := "application/pdf" dbmimetype := repository.NullCleanmimetype{ Valid: true, @@ -44,13 +43,21 @@ func TestExtract(t *testing.T) { } pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(dbCleanId).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(dbCleanId, database.MustToDBUUID(id), &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(dbCleanId, id, &inloc.Bucket, &inloc.Key, int64(1), dbmimetype, repository.NullCleanfailtype{}), ) - pool.ExpectQuery("name: AddDocumentTextEntry :one").WithArgs(pgxmock.AnyArg(), inloc.Bucket, inloc.Key, dbCleanId). + textId := uuid.New() + pool.ExpectBegin() + pool.ExpectQuery("name: GetDocumentTextExtractionByHash :one").WithArgs(dbCleanId, "example").WillReturnRows( + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}), + ) + pool.ExpectQuery("name: AddDocumentText :one").WithArgs(inloc.Bucket, inloc.Key, dbCleanId, "example"). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(uuid.New())), + AddRow(textId), ) + pool.ExpectExec("name: AddDocumentTextEntry :exec").WithArgs(textId, pgxmock.AnyArg()). + WillReturnResult(pgxmock.NewResult("", 1)) + pool.ExpectCommit() err = svc.extract(ctx, cleanId) require.NoError(t, err) @@ -58,14 +65,14 @@ func TestExtract(t *testing.T) { t.Run("fail clean", func(t *testing.T) { id := uuid.New() - cleanId := database.MustToDBUUID(uuid.New()) + cleanId := uuid.New() fail := repository.NullCleanfailtype{ Valid: true, Cleanfailtype: repository.CleanfailtypeInvalidMimetype, } - pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(cleanId, database.MustToDBUUID(id), nil, nil, int64(1), nil, fail), + AddRow(cleanId, id, nil, nil, int64(1), nil, fail), ) err = svc.extract(ctx, id) @@ -91,17 +98,65 @@ func TestExecuteExtraction(t *testing.T) { Bucket: "buck", Key: "key", } + extract := extraction{ + TextLocation: location, + Hash: "example", + } dbmimetype := repository.NullCleanmimetype{ Valid: true, Cleanmimetype: repository.CleanmimetypeApplicationPdf, } - pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(database.MustToDBUUID(id)).WillReturnRows( + pool.ExpectQuery("name: GetCleanEntry :one").WithArgs(id).WillReturnRows( pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "mimetype", "fail"}). - AddRow(database.MustToDBUUID(uuid.New()), database.MustToDBUUID(id), &location.Bucket, &location.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), + AddRow(uuid.New(), id, &location.Bucket, &location.Key, int32(1), dbmimetype, repository.NullCleanfailtype{}), ) outloc, err := svc.executeExtraction(ctx, id) require.NoError(t, err) - assert.EqualExportedValues(t, location, *outloc) + assert.EqualExportedValues(t, extract, *outloc) +} + +func TestStoreExtraction(t *testing.T) { + pool, err := pgxmock.NewPool() + require.NoError(t, err) + + cfg := &DocTextConfig{} + cfg.DBPool = pool + cfg.DBQueries = repository.New(pool) + + svc := Service{ + cfg: cfg, + } + + ctx := context.Background() + + t.Run("not existing", func(t *testing.T) { + cleanId := uuid.New() + dbCleanId := cleanId + textId := uuid.New() + extract := extraction{ + TextLocation: document.Location{ + Bucket: "buck", + Key: "key", + }, + Hash: "example", + } + + pool.ExpectBegin() + pool.ExpectQuery("name: GetDocumentTextExtractionByHash :one").WithArgs(dbCleanId, extract.Hash).WillReturnRows( + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}), + ) + pool.ExpectQuery("name: AddDocumentText :one").WithArgs(extract.TextLocation.Bucket, extract.TextLocation.Key, dbCleanId, "example"). + WillReturnRows( + pgxmock.NewRows([]string{"id"}). + AddRow(textId), + ) + pool.ExpectExec("name: AddDocumentTextEntry :exec").WithArgs(textId, pgxmock.AnyArg()). + WillReturnResult(pgxmock.NewResult("", 1)) + pool.ExpectCommit() + + err = svc.storeExtraction(ctx, cleanId, &extract) + require.NoError(t, err) + }) } diff --git a/internal/document/text/service.go b/internal/document/text/service.go index 87bdbfa0..fb5be95d 100644 --- a/internal/document/text/service.go +++ b/internal/document/text/service.go @@ -3,11 +3,13 @@ package documenttext import ( "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/querysync" + "queryorchestration/internal/serviceconfig/textract" ) type ConfigProvider interface { serviceconfig.ConfigProvider querysync.ConfigProvider + textract.ConfigProvider } type Service struct { diff --git a/internal/document/text/service_test.go b/internal/document/text/service_test.go index 69bb200e..3deddb45 100644 --- a/internal/document/text/service_test.go +++ b/internal/document/text/service_test.go @@ -6,6 +6,7 @@ import ( documenttext "queryorchestration/internal/document/text" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/querysync" + "queryorchestration/internal/serviceconfig/textract" "github.com/stretchr/testify/assert" ) @@ -13,6 +14,7 @@ import ( type DocTextConfig struct { serviceconfig.BaseConfig querysync.QuerySyncConfig + textract.TextractConfig } func TestService(t *testing.T) { diff --git a/internal/query/create.go b/internal/query/create.go index a9f58346..85111aed 100644 --- a/internal/query/create.go +++ b/internal/query/create.go @@ -4,14 +4,12 @@ import ( "context" "fmt" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" contextfull "queryorchestration/internal/query/types/contextFull" jsonextractor "queryorchestration/internal/query/types/jsonExtractor" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" ) func (s *Service) Create(ctx context.Context, entity *resultprocessor.Create) (uuid.UUID, error) { @@ -58,20 +56,20 @@ func (s *Service) submitCreate(ctx context.Context, entity *resultprocessor.Crea return uuid.Nil, err } - var dbID pgtype.UUID + var id uuid.UUID err = s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, qtx *repository.Queries) error { - dbID, err = qtx.CreateQuery(ctx, query.Type) + id, err = qtx.CreateQuery(ctx, query.Type) if err != nil { return err } - version, err := qtx.AddLatestQueryVersion(ctx, dbID) + version, err := qtx.AddLatestQueryVersion(ctx, id) if err != nil { return err } err = qtx.AddActiveQueryVersion(ctx, &repository.AddActiveQueryVersionParams{ - Queryid: dbID, + Queryid: id, Versionid: version, }) if err != nil { @@ -81,7 +79,7 @@ func (s *Service) submitCreate(ctx context.Context, entity *resultprocessor.Crea if query.RequiredQueryIDs != nil { for _, reqQuery := range *query.RequiredQueryIDs { err = qtx.AddRequiredQuery(ctx, &repository.AddRequiredQueryParams{ - Queryid: dbID, + Queryid: id, Requiredqueryid: reqQuery, Addedversion: version, }) @@ -93,7 +91,7 @@ func (s *Service) submitCreate(ctx context.Context, entity *resultprocessor.Crea if query.Config != nil { err = qtx.SetQueryConfig(ctx, &repository.SetQueryConfigParams{ - Queryid: dbID, + Queryid: id, Config: *query.Config, Addedversion: version, }) @@ -108,11 +106,6 @@ func (s *Service) submitCreate(ctx context.Context, entity *resultprocessor.Crea return uuid.Nil, err } - id, err := database.ToUUID(dbID) - if err != nil { - return uuid.Nil, err - } - return id, nil } @@ -130,7 +123,7 @@ func (s *Service) getCreator(qType resultprocessor.Type) (resultprocessor.Creato type createQuery struct { Type repository.Querytype - RequiredQueryIDs *[]pgtype.UUID + RequiredQueryIDs *[]uuid.UUID Config *[]byte } @@ -140,9 +133,9 @@ func parseCreateQuery(q *resultprocessor.Create) (*createQuery, error) { return nil, err } - var reqIDs *[]pgtype.UUID + var reqIDs *[]uuid.UUID if q.RequiredQueryIDs != nil { - tIDs := database.MustToDBUUIDArray(*q.RequiredQueryIDs) + tIDs := *q.RequiredQueryIDs reqIDs = &tIDs } diff --git a/internal/query/create_test.go b/internal/query/create_test.go index ca42a242..82c8d13d 100644 --- a/internal/query/create_test.go +++ b/internal/query/create_test.go @@ -5,7 +5,6 @@ import ( "errors" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -47,26 +46,26 @@ func TestCreate(t *testing.T) { dbType, err := resultprocessor.ToDBQueryType(create.Type) require.NoError(t, err) - pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(database.MustToDBUUIDArray(*create.RequiredQueryIDs)).WillReturnRows( + pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(*create.RequiredQueryIDs).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}).AddRow(true), ) pool.ExpectBeginTx(pgx.TxOptions{}) pool.ExpectQuery("name: CreateQuery :one").WithArgs(dbType).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(q.ID)), + AddRow(q.ID), ) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(q.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(q.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), int32(1)). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) for _, req := range *create.RequiredQueryIDs { - pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(database.MustToDBUUID(q.ID), database.MustToDBUUID(req), int32(1)). + pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(q.ID, req, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) } - pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(database.MustToDBUUID(q.ID), []byte(*create.Config), int32(1)). + pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(q.ID, []byte(*create.Config), int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -99,13 +98,13 @@ func TestCreateMinimal(t *testing.T) { pool.ExpectBeginTx(pgx.TxOptions{}) pool.ExpectQuery("name: CreateQuery :one").WithArgs(dbType).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(q.ID)), + AddRow(q.ID), ) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(q.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(q.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), int32(1)). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() diff --git a/internal/query/createprivate_test.go b/internal/query/createprivate_test.go index a764f9ea..b61efb25 100644 --- a/internal/query/createprivate_test.go +++ b/internal/query/createprivate_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/serviceconfig" @@ -51,7 +50,7 @@ func TestParseCreateQuery(t *testing.T) { resultQuery, err := parseCreateQuery(cQuery) require.NoError(t, err) - rQIDs := database.MustToDBUUIDArray(*cQuery.RequiredQueryIDs) + rQIDs := *cQuery.RequiredQueryIDs qcfg := []byte(*cQuery.Config) assert.EqualExportedValues(t, createQuery{ Type: repository.QuerytypeContextFull, @@ -105,19 +104,19 @@ func TestSubmitCreate(t *testing.T) { pool.ExpectBeginTx(pgx.TxOptions{}) pool.ExpectQuery("name: CreateQuery :one").WithArgs(dbType).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(q.ID)), + AddRow(q.ID), ) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(q.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(q.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), int32(1)). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) for _, req := range *create.RequiredQueryIDs { - pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(database.MustToDBUUID(q.ID), database.MustToDBUUID(req), int32(1)). + pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(q.ID, req, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) } - pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(database.MustToDBUUID(q.ID), []byte(*create.Config), int32(1)). + pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(q.ID, []byte(*create.Config), int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -150,13 +149,13 @@ func TestSubmitCreateNoReqsOrConfig(t *testing.T) { pool.ExpectBeginTx(pgx.TxOptions{}) pool.ExpectQuery("name: CreateQuery :one").WithArgs(dbType).WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(q.ID)), + AddRow(q.ID), ) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(q.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(q.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), int32(1)). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, int32(1)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -181,7 +180,7 @@ func TestNormalizeCreate(t *testing.T) { RequiredQueryIDs: &[]uuid.UUID{}, } - dbids := database.MustToDBUUIDArray(*create.RequiredQueryIDs) + dbids := *create.RequiredQueryIDs pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). diff --git a/internal/query/get.go b/internal/query/get.go index a1ed0fc3..1b016679 100644 --- a/internal/query/get.go +++ b/internal/query/get.go @@ -3,7 +3,6 @@ package query import ( "context" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" @@ -21,7 +20,7 @@ type Query struct { func (s *Service) GetWithVersion(ctx context.Context, id uuid.UUID, version int32) (*Query, error) { query, err := s.cfg.GetDBQueries().GetQueryWithVersion(ctx, &repository.GetQueryWithVersionParams{ - ID: database.MustToDBUUID(id), + ID: &id, Version: &version, }) if err != nil { @@ -32,7 +31,7 @@ func (s *Service) GetWithVersion(ctx context.Context, id uuid.UUID, version int3 } func (s *Service) Get(ctx context.Context, id uuid.UUID) (*Query, error) { - query, err := s.cfg.GetDBQueries().GetQuery(ctx, database.MustToDBUUID(id)) + query, err := s.cfg.GetDBQueries().GetQuery(ctx, id) if err != nil { return nil, err } diff --git a/internal/query/get_test.go b/internal/query/get_test.go index cfdc663e..c16894d6 100644 --- a/internal/query/get_test.go +++ b/internal/query/get_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -38,11 +37,11 @@ func TestGet(t *testing.T) { Config: &config, } - dbReqIDs := database.MustToDBUUIDArray(*query.RequiredQueryIDs) + dbReqIDs := *query.RequiredQueryIDs - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.ActiveVersion, query.LatestVersion, []byte(config), dbReqIDs), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.ActiveVersion, query.LatestVersion, []byte(config), dbReqIDs), ) returnQuery, err := svc.Get(ctx, query.ID) @@ -75,11 +74,11 @@ func TestGetWithVersion(t *testing.T) { version := int32(2) - dbReqIDs := database.MustToDBUUIDArray(*query.RequiredQueryIDs) + dbReqIDs := *query.RequiredQueryIDs - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(query.ID), &version).WillReturnRows( + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(&query.ID, &version).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.ActiveVersion, query.LatestVersion, []byte(config), dbReqIDs), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.ActiveVersion, query.LatestVersion, []byte(config), dbReqIDs), ) returnQuery, err := svc.GetWithVersion(ctx, query.ID, version) diff --git a/internal/query/list.go b/internal/query/list.go index 6da607b8..5f9ba98e 100644 --- a/internal/query/list.go +++ b/internal/query/list.go @@ -3,8 +3,6 @@ package query import ( "context" - "queryorchestration/internal/database" - "github.com/google/uuid" ) @@ -23,7 +21,7 @@ func (s *Service) List(ctx context.Context) ([]*Query, error) { } func (s *Service) ListById(ctx context.Context, ids []uuid.UUID) ([]*Query, error) { - dbQueries, err := s.cfg.GetDBQueries().ListQueriesById(ctx, database.MustToDBUUIDArray(ids)) + dbQueries, err := s.cfg.GetDBQueries().ListQueriesById(ctx, ids) if err != nil { return nil, err } diff --git a/internal/query/list_test.go b/internal/query/list_test.go index b9a5b0d1..97777821 100644 --- a/internal/query/list_test.go +++ b/internal/query/list_test.go @@ -4,14 +4,12 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/serviceconfig" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/require" @@ -40,11 +38,11 @@ func TestList(t *testing.T) { Config: &config, } - dbReqIDs := database.MustToDBUUIDArray(*q.RequiredQueryIDs) + dbReqIDs := *q.RequiredQueryIDs pool.ExpectQuery("name: ListQueries :many").WithArgs().WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(q.ID), repository.QuerytypeJsonExtractor, q.ActiveVersion, q.LatestVersion, []byte(config), dbReqIDs), + AddRow(q.ID, repository.QuerytypeJsonExtractor, q.ActiveVersion, q.LatestVersion, []byte(config), dbReqIDs), ) resList, err := svc.List(ctx) @@ -75,11 +73,11 @@ func TestListById(t *testing.T) { Config: &config, } - dbReqIDs := database.MustToDBUUIDArray(*q.RequiredQueryIDs) + dbReqIDs := *q.RequiredQueryIDs - pool.ExpectQuery("name: ListQueriesById :many").WithArgs([]pgtype.UUID{database.MustToDBUUID(q.ID)}).WillReturnRows( + pool.ExpectQuery("name: ListQueriesById :many").WithArgs([]uuid.UUID{q.ID}).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(q.ID), repository.QuerytypeJsonExtractor, q.ActiveVersion, q.LatestVersion, []byte(config), dbReqIDs), + AddRow(q.ID, repository.QuerytypeJsonExtractor, q.ActiveVersion, q.LatestVersion, []byte(config), dbReqIDs), ) resList, err := svc.ListById(ctx, []uuid.UUID{q.ID}) diff --git a/internal/query/normalize.go b/internal/query/normalize.go index e05b96e4..c99e1b50 100644 --- a/internal/query/normalize.go +++ b/internal/query/normalize.go @@ -7,7 +7,6 @@ import ( "fmt" "strings" - "queryorchestration/internal/database" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/validation" @@ -72,7 +71,7 @@ func (s *Service) NormalizeQueryIDs(ctx context.Context, ids RequiredQueryIDs) e dedup := validation.DeduplicateArray(*ide) ids.SetRequiredQueryIDs(&dedup) - dbids := database.MustToDBUUIDArray(dedup) + dbids := dedup exist, err := s.cfg.GetDBQueries().AllQueriesExist(ctx, dbids) if err != nil { diff --git a/internal/query/normalize_test.go b/internal/query/normalize_test.go index d2ec9c80..2b246e01 100644 --- a/internal/query/normalize_test.go +++ b/internal/query/normalize_test.go @@ -5,7 +5,6 @@ import ( "errors" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/serviceconfig" @@ -97,7 +96,7 @@ func TestNormalizeQueryIDs(t *testing.T) { ids := []uuid.UUID{uuid.New()} entity.RequiredQueryIDs = &ids - dbids := database.MustToDBUUIDArray(*entity.RequiredQueryIDs) + dbids := *entity.RequiredQueryIDs pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). @@ -127,7 +126,7 @@ func TestNormalizeQueryIDs(t *testing.T) { singleid := uuid.New() entity.RequiredQueryIDs = &[]uuid.UUID{singleid, singleid} outids := []uuid.UUID{singleid} - dbids = database.MustToDBUUIDArray(outids) + dbids = outids pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). diff --git a/internal/query/parse.go b/internal/query/parse.go index 1d3d8273..aa2aee39 100644 --- a/internal/query/parse.go +++ b/internal/query/parse.go @@ -1,7 +1,6 @@ package query import ( - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" @@ -30,15 +29,6 @@ func ParseQuery(q *Query) *resultprocessor.Query { } func ParseFullActiveQuery(q *repository.Fullactivequery) (*Query, error) { - var reqQueryIDs *[]uuid.UUID - if len(q.Requiredids) > 0 { - rQ, err := database.ToUUIDArray(q.Requiredids) - if err != nil { - return nil, err - } - reqQueryIDs = &rQ - } - qType, err := resultprocessor.ParseDBType(q.Type) if err != nil { return nil, err @@ -50,12 +40,17 @@ func ParseFullActiveQuery(q *repository.Fullactivequery) (*Query, error) { scfg = &s } + var reqIds *[]uuid.UUID + if len(q.Requiredids) > 0 { + reqIds = &q.Requiredids + } + return &Query{ - ID: database.MustToUUID(q.ID), + ID: q.ID, ActiveVersion: q.Activeversion, LatestVersion: q.Latestversion, Type: qType, - RequiredQueryIDs: reqQueryIDs, + RequiredQueryIDs: reqIds, Config: scfg, }, nil } diff --git a/internal/query/parse_test.go b/internal/query/parse_test.go index 4be21671..733aae61 100644 --- a/internal/query/parse_test.go +++ b/internal/query/parse_test.go @@ -3,13 +3,11 @@ package query_test import ( "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -39,12 +37,12 @@ func TestParseQuery(t *testing.T) { func TestParseFullActiveQuery(t *testing.T) { q := &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: int32(1), Latestversion: int32(2), - Requiredids: []pgtype.UUID{ - database.MustToDBUUID(uuid.New()), + Requiredids: []uuid.UUID{ + uuid.New(), }, Config: []byte("example"), } @@ -53,12 +51,12 @@ func TestParseFullActiveQuery(t *testing.T) { require.NoError(t, err) bcfg := string(q.Config) assert.EqualExportedValues(t, query.Query{ - ID: database.MustToUUID(q.ID), + ID: q.ID, Type: resultprocessor.TypeContextFull, ActiveVersion: q.Activeversion, LatestVersion: q.Latestversion, RequiredQueryIDs: &[]uuid.UUID{ - database.MustToUUID(q.Requiredids[0]), + q.Requiredids[0], }, Config: &bcfg, }, *out) @@ -66,7 +64,7 @@ func TestParseFullActiveQuery(t *testing.T) { func TestFullActiveQueryEmpty(t *testing.T) { dbQuery := &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: int32(1), Latestversion: int32(2), @@ -75,7 +73,7 @@ func TestFullActiveQueryEmpty(t *testing.T) { out, err := query.ParseFullActiveQuery(dbQuery) require.NoError(t, err) assert.EqualExportedValues(t, query.Query{ - ID: database.MustToUUID(dbQuery.ID), + ID: dbQuery.ID, Type: resultprocessor.TypeContextFull, ActiveVersion: int32(1), LatestVersion: int32(2), @@ -84,7 +82,7 @@ func TestFullActiveQueryEmpty(t *testing.T) { func TestFullActiveQueryWithNullUUID(t *testing.T) { dbQuery := &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: int32(1), Latestversion: int32(2), @@ -93,7 +91,7 @@ func TestFullActiveQueryWithNullUUID(t *testing.T) { out, err := query.ParseFullActiveQuery(dbQuery) require.NoError(t, err) assert.EqualExportedValues(t, query.Query{ - ID: database.MustToUUID(dbQuery.ID), + ID: dbQuery.ID, Type: resultprocessor.TypeContextFull, ActiveVersion: int32(1), LatestVersion: int32(2), @@ -103,7 +101,7 @@ func TestFullActiveQueryWithNullUUID(t *testing.T) { func TestFullActiveQueryArray(t *testing.T) { dbQueries := []*repository.Fullactivequery{ { - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: int32(1), Latestversion: int32(2), @@ -114,7 +112,7 @@ func TestFullActiveQueryArray(t *testing.T) { require.NoError(t, err) assert.EqualExportedValues(t, []*query.Query{ { - ID: database.MustToUUID(dbQueries[0].ID), + ID: dbQueries[0].ID, Type: resultprocessor.TypeContextFull, ActiveVersion: int32(1), LatestVersion: int32(2), diff --git a/internal/query/result/get.go b/internal/query/result/get.go index 7f18345b..1399c231 100644 --- a/internal/query/result/get.go +++ b/internal/query/result/get.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" contextfull "queryorchestration/internal/query/types/contextFull" @@ -23,9 +22,9 @@ type GetValueWithVersionParams struct { func (s *Service) GetValueWithVersion(ctx context.Context, params *GetValueWithVersionParams) (resultprocessor.Value, error) { res, err := s.cfg.GetDBQueries().GetResultValueWithVersion(ctx, &repository.GetResultValueWithVersionParams{ - Queryid: database.MustToDBUUID(params.QueryID), + Queryid: ¶ms.QueryID, Queryversion: ¶ms.QueryVersion, - Documentid: database.MustToDBUUID(params.DocumentID), + Documentid: ¶ms.DocumentID, }) if err != nil { return nil, err diff --git a/internal/query/result/get_test.go b/internal/query/result/get_test.go index 0d6787ae..9676f806 100644 --- a/internal/query/result/get_test.go +++ b/internal/query/result/get_test.go @@ -4,14 +4,12 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" jsonextractor "queryorchestration/internal/query/types/jsonExtractor" "queryorchestration/internal/serviceconfig" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -49,10 +47,10 @@ func TestGetValueWithVersion(t *testing.T) { } value := "exaple_value" - pool.ExpectQuery("name: GetResultValueWithVersion :one").WithArgs(database.MustToDBUUID(params.QueryID), ¶ms.QueryVersion, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: GetResultValueWithVersion :one").WithArgs(¶ms.QueryID, ¶ms.QueryVersion, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "value"}). - AddRow(pgtype.UUID{}, &value), + AddRow(&uuid.UUID{}, &value), ) val, err := svc.GetValueWithVersion(ctx, params) diff --git a/internal/query/result/process.go b/internal/query/result/process.go index 80ec1865..1d06c6fc 100644 --- a/internal/query/result/process.go +++ b/internal/query/result/process.go @@ -7,7 +7,6 @@ import ( "fmt" "log/slog" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" contextfull "queryorchestration/internal/query/types/contextFull" @@ -70,8 +69,8 @@ func (s *Service) listRequiredValues(ctx context.Context, p *Process, query *res } qResults, err := s.cfg.GetDBQueries().ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: database.MustToDBUUID(p.QueryID), - Documentid: database.MustToDBUUID(p.DocumentID), + Queryid: &p.QueryID, + Documentid: &p.DocumentID, Version: &p.QueryVersion, }) if err != nil && !errors.Is(err, sql.ErrNoRows) { diff --git a/internal/query/result/process_test.go b/internal/query/result/process_test.go index 295b3f75..9278a44c 100644 --- a/internal/query/result/process_test.go +++ b/internal/query/result/process_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -46,17 +45,17 @@ func TestProcess(t *testing.T) { QueryVersion: query.Version, } - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(query.ID), &query.Version).WillReturnRows( + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(&query.ID, &query.Version).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), database.MustToDBUUIDArray(*query.RequiredQueryIDs)), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), *query.RequiredQueryIDs), ) strVal := `{"examplekey":"example_value"}` - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(uuid.New()), database.MustToDBUUID(query.ID), repository.QuerytypeContextFull, &strVal), + AddRow(&uuid.UUID{}, query.ID, repository.QuerytypeContextFull, &strVal), ) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(qcfg)), ) @@ -109,10 +108,10 @@ func TestListRequiredValue(t *testing.T) { strVal := "axe_value" - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(uuid.New()), database.MustToDBUUID((*query.RequiredQueryIDs)[0]), repository.QuerytypeJsonExtractor, &strVal), + AddRow(&uuid.UUID{}, (*query.RequiredQueryIDs)[0], repository.QuerytypeJsonExtractor, &strVal), ) pr, err = svc.listRequiredValues(ctx, ¶ms, query) @@ -141,7 +140,7 @@ func TestParseQueryRequirementValueArray(t *testing.T) { exval := "exampleval" in := []*repository.ListQueryRequirementValuesRow{ { - Queryid: database.MustToDBUUID(uuid.New()), + Queryid: uuid.New(), Value: &exval, Type: repository.QuerytypeJsonExtractor, }, diff --git a/internal/query/result/processor/parse.go b/internal/query/result/processor/parse.go index a858f6c1..8f29dbf4 100644 --- a/internal/query/result/processor/parse.go +++ b/internal/query/result/processor/parse.go @@ -3,7 +3,6 @@ package resultprocessor import ( "fmt" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "github.com/google/uuid" @@ -67,22 +66,21 @@ func ToDBNullQueryType(t Type) (repository.NullQuerytype, error) { } func ParseDBCollectorQuery(q *repository.Collectorquerydependencytree) (*Query, error) { - var reqQueryIDs *[]uuid.UUID - if len(q.Requiredids) > 0 { - ids := database.MustToUUIDArray(q.Requiredids) - reqQueryIDs = &ids - } - qType, err := ParseDBType(q.Type) if err != nil { return nil, err } + var reqIds *[]uuid.UUID + if len(q.Requiredids) > 0 { + reqIds = &q.Requiredids + } + return &Query{ - ID: database.MustToUUID(q.Queryid), + ID: *q.Queryid, Version: q.Queryversion, Type: qType, - RequiredQueryIDs: reqQueryIDs, + RequiredQueryIDs: reqIds, }, nil } @@ -96,23 +94,22 @@ func ParseFullQuery(qs *repository.Fullactivequery) (*Query, error) { return nil, err } - var rids *[]uuid.UUID - if len(qs.Requiredids) > 0 { - r := database.MustToUUIDArray(qs.Requiredids) - rids = &r - } - var cfg *string if qs.Config != nil { c := string(qs.Config) cfg = &c } + var reqIds *[]uuid.UUID + if len(qs.Requiredids) > 0 { + reqIds = &qs.Requiredids + } + return &Query{ - ID: database.MustToUUID(qs.ID), + ID: qs.ID, Type: qt, Version: qs.Activeversion, - RequiredQueryIDs: rids, + RequiredQueryIDs: reqIds, Config: cfg, }, nil } diff --git a/internal/query/result/processor/parse_test.go b/internal/query/result/processor/parse_test.go index 880cb8f6..6eab29b6 100644 --- a/internal/query/result/processor/parse_test.go +++ b/internal/query/result/processor/parse_test.go @@ -3,21 +3,19 @@ package resultprocessor_test import ( "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestParseDBCollectorQuery(t *testing.T) { dbResult := repository.Collectorquerydependencytree{ - Clientid: pgtype.UUID{}, - Queryid: pgtype.UUID{}, - Requiredids: []pgtype.UUID{}, + Clientid: uuid.UUID{}, + Queryid: &uuid.UUID{}, + Requiredids: []uuid.UUID{}, Type: repository.QuerytypeJsonExtractor, Queryversion: 1, } @@ -118,7 +116,7 @@ func TestParseFullQuery(t *testing.T) { assert.Nil(t, out) q = &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: 1, Latestversion: 2, @@ -126,36 +124,36 @@ func TestParseFullQuery(t *testing.T) { out, err = resultprocessor.ParseFullQuery(q) require.NoError(t, err) - assert.EqualExportedValues(t, &resultprocessor.Query{ - ID: database.MustToUUID(q.ID), + assert.EqualExportedValues(t, resultprocessor.Query{ + ID: q.ID, Type: resultprocessor.TypeContextFull, Version: 1, - }, out) + }, *out) q = &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: 1, Latestversion: 2, - Requiredids: []pgtype.UUID{}, + Requiredids: []uuid.UUID{}, } out, err = resultprocessor.ParseFullQuery(q) require.NoError(t, err) assert.EqualExportedValues(t, &resultprocessor.Query{ - ID: database.MustToUUID(q.ID), + ID: q.ID, Type: resultprocessor.TypeContextFull, Version: 1, }, out) q = &repository.Fullactivequery{ - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: 1, Latestversion: 2, Config: []byte("hello"), - Requiredids: []pgtype.UUID{ - database.MustToDBUUID(uuid.New()), + Requiredids: []uuid.UUID{ + uuid.New(), }, } @@ -163,11 +161,11 @@ func TestParseFullQuery(t *testing.T) { require.NoError(t, err) cfg := "hello" assert.EqualExportedValues(t, &resultprocessor.Query{ - ID: database.MustToUUID(q.ID), + ID: q.ID, Type: resultprocessor.TypeContextFull, Version: 1, Config: &cfg, - RequiredQueryIDs: &[]uuid.UUID{database.MustToUUID(q.Requiredids[0])}, + RequiredQueryIDs: &[]uuid.UUID{q.Requiredids[0]}, }, out) } @@ -179,7 +177,7 @@ func TestParseFullQueryArray(t *testing.T) { q = []*repository.Fullactivequery{ { - ID: database.MustToDBUUID(uuid.New()), + ID: uuid.New(), Type: repository.QuerytypeContextFull, Activeversion: 1, Latestversion: 2, @@ -190,7 +188,7 @@ func TestParseFullQueryArray(t *testing.T) { require.NoError(t, err) assert.EqualExportedValues(t, []*resultprocessor.Query{ { - ID: database.MustToUUID(q[0].ID), + ID: q[0].ID, Type: resultprocessor.TypeContextFull, Version: 1, }, diff --git a/internal/query/result/set/set.go b/internal/query/result/set/set.go index e3f2a2ce..7b843677 100644 --- a/internal/query/result/set/set.go +++ b/internal/query/result/set/set.go @@ -6,9 +6,9 @@ import ( "errors" "log/slog" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query/result" + resultprocessor "queryorchestration/internal/query/result/processor" "github.com/google/uuid" ) @@ -19,7 +19,7 @@ type Set struct { } func (s *Service) Set(ctx context.Context, params *Set) error { - dbid := database.MustToDBUUID(params.DocumentID) + dbid := params.DocumentID textVersion, err := s.cfg.GetDBQueries().GetTextEntryByDocId(ctx, dbid) if err != nil { return err @@ -39,38 +39,7 @@ func (s *Service) Set(ctx context.Context, params *Set) error { return err } - err = s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { - id, err := q.AddResult(ctx, &repository.AddResultParams{ - Queryid: database.MustToDBUUID(params.QueryID), - Value: value.GetStoreValue(), - Queryversion: query.ActiveVersion, - Textentryid: textVersion.ID, - }) - if err != nil { - return err - } - - qResults, err := q.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ - Queryid: database.MustToDBUUID(params.QueryID), - Documentid: database.MustToDBUUID(params.DocumentID), - Version: &query.ActiveVersion, - }) - if err != nil && !errors.Is(err, sql.ErrNoRows) { - return err - } - - for _, result := range qResults { - err = q.AddResultDependency(ctx, &repository.AddResultDependencyParams{ - Resultid: id, - Requiredresultid: result.ID, - }) - if err != nil { - return err - } - } - - return nil - }) + err = s.storeResult(ctx, textVersion, params, query.ActiveVersion, value) if err != nil { return err } @@ -80,14 +49,49 @@ func (s *Service) Set(ctx context.Context, params *Set) error { return s.informQueryDependents(ctx, params) } +func (s *Service) storeResult(ctx context.Context, textVersion *repository.Currenttextentry, params *Set, activeVersion int32, value resultprocessor.Value) error { + return s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { + id, err := q.AddResult(ctx, &repository.AddResultParams{ + Queryid: params.QueryID, + Value: value.GetStoreValue(), + Queryversion: activeVersion, + Textentryid: textVersion.ID, + }) + if err != nil { + return err + } + + qResults, err := q.ListQueryRequirementValues(ctx, &repository.ListQueryRequirementValuesParams{ + Queryid: ¶ms.QueryID, + Documentid: ¶ms.DocumentID, + Version: &activeVersion, + }) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + + for _, result := range qResults { + err = q.AddResultDependency(ctx, &repository.AddResultDependencyParams{ + Resultid: id, + Requiredresultid: *result.ID, + }) + if err != nil { + return err + } + } + + return nil + }) +} + func (s *Service) informQueryDependents(ctx context.Context, params *Set) error { ids, err := s.cfg.GetDBQueries().ListQueryDirectDependentsByDocumentID(ctx, &repository.ListQueryDirectDependentsByDocumentIDParams{ - Documentid: database.MustToDBUUID(params.DocumentID), - Queryid: database.MustToDBUUID(params.QueryID), + Documentid: params.DocumentID, + Queryid: params.QueryID, }) if err != nil { return err } - return s.svc.Sync.TriggerMultiSync(ctx, params.DocumentID, database.MustToUUIDArray(ids)) + return s.svc.Sync.TriggerMultiSync(ctx, params.DocumentID, ids) } diff --git a/internal/query/result/set/set_test.go b/internal/query/result/set/set_test.go index 136c4ffa..873a4a4d 100644 --- a/internal/query/result/set/set_test.go +++ b/internal/query/result/set/set_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" "queryorchestration/internal/query/result" @@ -53,10 +52,11 @@ func TestSet(t *testing.T) { } qcfg := "{\"path\":\"examplekey\"}" + requiredQuery := uuid.New() query := &resultprocessor.Query{ ID: uuid.New(), Version: 2, - RequiredQueryIDs: &[]uuid.UUID{uuid.New()}, + RequiredQueryIDs: &[]uuid.UUID{requiredQuery}, Config: &qcfg, } params := Set{ @@ -65,56 +65,56 @@ func TestSet(t *testing.T) { } textEntryId := uuid.New() - pool.ExpectQuery("name: GetTextEntryByDocId :one").WithArgs(database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: GetTextEntryByDocId :one").WithArgs(params.DocumentID). WillReturnRows( - pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "cleanEntryId"}). - AddRow(database.MustToDBUUID(textEntryId), database.MustToDBUUID(params.DocumentID), "buket", "/i/am/here", int32(1), database.MustToDBUUID(uuid.New())), + pgxmock.NewRows([]string{"id", "documentId", "bucket", "key", "version", "hash", "cleanEntryId"}). + AddRow(textEntryId, params.DocumentID, "buket", "/i/am/here", int32(1), "example", uuid.New()), ) - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), database.MustToDBUUIDArray(*query.RequiredQueryIDs)), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), *query.RequiredQueryIDs), ) - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(query.ID), &query.Version).WillReturnRows( + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(&query.ID, &query.Version).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(query.ID), repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), database.MustToDBUUIDArray(*query.RequiredQueryIDs)), + AddRow(query.ID, repository.QuerytypeJsonExtractor, query.Version, query.Version, []byte(*query.Config), *query.RequiredQueryIDs), ) requiredResultId := uuid.New() strVal := "{\"examplekey\":\"example_value\"}" - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(requiredResultId), database.MustToDBUUID((*query.RequiredQueryIDs)[0]), repository.QuerytypeContextFull, &strVal), + AddRow(&requiredResultId, (*query.RequiredQueryIDs)[0], repository.QuerytypeContextFull, &strVal), ) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)).WillReturnRows( + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID).WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(qcfg)), ) pool.ExpectBegin() resultId := uuid.New() - pool.ExpectQuery("name: AddResult :one").WithArgs(database.MustToDBUUID(query.ID), pgxmock.AnyArg(), database.MustToDBUUID(textEntryId), query.Version). + pool.ExpectQuery("name: AddResult :one").WithArgs(query.ID, pgxmock.AnyArg(), textEntryId, query.Version). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(resultId)), + AddRow(resultId), ) - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(query.ID), &query.Version, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(&query.ID, &query.Version, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(requiredResultId), database.MustToDBUUID((*query.RequiredQueryIDs)[0]), repository.QuerytypeContextFull, &strVal), + AddRow(&requiredResultId, (*query.RequiredQueryIDs)[0], repository.QuerytypeContextFull, &strVal), ) - pool.ExpectExec("name: AddResultDependency :exec").WithArgs(database.MustToDBUUID(resultId), database.MustToDBUUID(requiredResultId)). + pool.ExpectExec("name: AddResultDependency :exec").WithArgs(resultId, requiredResultId). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() - pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(database.MustToDBUUID(params.QueryID), database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(params.QueryID, params.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"queryId"}). - AddRow(database.MustToDBUUID((*query.RequiredQueryIDs)[0])), + AddRow(&requiredQuery), ) mockSQS.EXPECT(). SendMessage( mock.Anything, mock.MatchedBy(func(in *sqs.SendMessageInput) bool { - return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", params.DocumentID.String(), (*query.RequiredQueryIDs)[0].String()) + return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", params.DocumentID.String(), requiredQuery.String()) }), mock.Anything, ). @@ -148,20 +148,22 @@ func TestInformQueryDependents(t *testing.T) { }, } + reqOne := uuid.New() + reqTwo := uuid.New() qIds := []uuid.UUID{ - uuid.New(), - uuid.New(), + reqOne, + reqTwo, } params := &Set{ DocumentID: uuid.New(), QueryID: uuid.New(), } - pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(database.MustToDBUUID(params.QueryID), database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryDirectDependentsByDocumentID :many").WithArgs(params.QueryID, params.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"queryId"}). - AddRow(database.MustToDBUUID(qIds[0])). - AddRow(database.MustToDBUUID(qIds[1])), + AddRow(&reqOne). + AddRow(&reqTwo), ) mockSQS.EXPECT(). diff --git a/internal/query/result/sync/trigger.go b/internal/query/result/sync/trigger.go index 260464d5..1f1f2e76 100644 --- a/internal/query/result/sync/trigger.go +++ b/internal/query/result/sync/trigger.go @@ -13,11 +13,11 @@ type Body struct { QueryID uuid.UUID `json:"query_id" validate:"required,uuid"` } -func (s *Service) TriggerMultiSync(ctx context.Context, documentID uuid.UUID, queryIDs []uuid.UUID) error { +func (s *Service) TriggerMultiSync(ctx context.Context, documentID uuid.UUID, queryIDs []*uuid.UUID) error { for _, id := range queryIDs { err := s.TriggerSync(ctx, &Body{ DocumentID: documentID, - QueryID: id, + QueryID: *id, }) if err != nil { diff --git a/internal/query/result/sync/trigger_test.go b/internal/query/result/sync/trigger_test.go index 184a87ee..c56257a5 100644 --- a/internal/query/result/sync/trigger_test.go +++ b/internal/query/result/sync/trigger_test.go @@ -75,16 +75,14 @@ func TestTriggerMultiSync(t *testing.T) { } docId := uuid.New() - qIds := []uuid.UUID{ - uuid.New(), - uuid.New(), - } + queryIDOne := uuid.New() + queryIDTwo := uuid.New() mockSQS.EXPECT(). SendMessage( mock.Anything, mock.MatchedBy(func(in *sqs.SendMessageInput) bool { - return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", docId.String(), qIds[0].String()) + return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", docId.String(), queryIDOne.String()) }), mock.Anything, ). @@ -94,12 +92,12 @@ func TestTriggerMultiSync(t *testing.T) { SendMessage( mock.Anything, mock.MatchedBy(func(in *sqs.SendMessageInput) bool { - return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", docId.String(), qIds[1].String()) + return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", docId.String(), queryIDTwo.String()) }), mock.Anything, ). Return(&sqs.SendMessageOutput{}, nil) - err = svc.TriggerMultiSync(ctx, docId, qIds) + err = svc.TriggerMultiSync(ctx, docId, []*uuid.UUID{&queryIDOne, &queryIDTwo}) require.NoError(t, err) } diff --git a/internal/query/sync/sync.go b/internal/query/sync/sync.go index 18a27927..3b96242f 100644 --- a/internal/query/sync/sync.go +++ b/internal/query/sync/sync.go @@ -4,15 +4,11 @@ import ( "context" "log/slog" - "queryorchestration/internal/database" - "github.com/google/uuid" ) func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { - dbid := database.MustToDBUUID(id) - - isextracted, err := s.cfg.GetDBQueries().IsDocumentTextExtracted(ctx, dbid) + isextracted, err := s.cfg.GetDBQueries().IsDocumentTextExtracted(ctx, id) if err != nil { return err } else if !isextracted { @@ -20,17 +16,12 @@ func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { return nil } - unsyncedQueries, err := s.cfg.GetDBQueries().ListUnsyncedNoDepsQueriesByDocId(ctx, dbid) + unsyncedQueries, err := s.cfg.GetDBQueries().ListUnsyncedNoDepsQueriesByDocId(ctx, &id) if err != nil { return err } slog.Debug("unsynced queries", "document_id", id.String(), "queries", unsyncedQueries) - ids := make([]uuid.UUID, len(unsyncedQueries)) - for i, dbId := range unsyncedQueries { - ids[i] = database.MustToUUID(dbId) - } - - return s.svc.ResultSync.TriggerMultiSync(ctx, id, ids) + return s.svc.ResultSync.TriggerMultiSync(ctx, id, unsyncedQueries) } diff --git a/internal/query/sync/sync_test.go b/internal/query/sync/sync_test.go index 8605e20e..2bbe21fd 100644 --- a/internal/query/sync/sync_test.go +++ b/internal/query/sync/sync_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultsync "queryorchestration/internal/query/result/sync" "queryorchestration/internal/serviceconfig" @@ -44,28 +43,26 @@ func TestSync(t *testing.T) { t.Run("valid", func(t *testing.T) { id := uuid.New() - qs := []uuid.UUID{ - uuid.New(), - uuid.New(), - } + reqOne := uuid.New() + reqTwo := uuid.New() - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(id). WillReturnRows( pgxmock.NewRows([]string{"isextracted"}). AddRow(true), ) - pool.ExpectQuery("name: ListUnsyncedNoDepsQueriesByDocId :many").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: ListUnsyncedNoDepsQueriesByDocId :many").WithArgs(&id). WillReturnRows( pgxmock.NewRows([]string{"id"}). - AddRow(database.MustToDBUUID(qs[0])). - AddRow(database.MustToDBUUID(qs[1])), + AddRow(&reqOne). + AddRow(&reqTwo), ) mockSQS.EXPECT(). SendMessage( mock.Anything, mock.MatchedBy(func(in *sqs.SendMessageInput) bool { - return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", id.String(), qs[0].String()) + return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", id.String(), reqOne.String()) }), mock.Anything, ). @@ -75,7 +72,7 @@ func TestSync(t *testing.T) { SendMessage( mock.Anything, mock.MatchedBy(func(in *sqs.SendMessageInput) bool { - return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", id.String(), qs[1].String()) + return *in.QueueUrl == cfg.QueryURL && *in.MessageBody == fmt.Sprintf("{\"document_id\":\"%s\",\"query_id\":\"%s\"}", id.String(), reqTwo.String()) }), mock.Anything, ). @@ -86,7 +83,7 @@ func TestSync(t *testing.T) { t.Run("not extracted", func(t *testing.T) { id := uuid.New() - pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(database.MustToDBUUID(id)). + pool.ExpectQuery("name: IsDocumentTextExtracted :one").WithArgs(id). WillReturnRows( pgxmock.NewRows([]string{"isextracted"}). AddRow(false), diff --git a/internal/query/test/test_test.go b/internal/query/test/test_test.go index e6376182..8a6c3440 100644 --- a/internal/query/test/test_test.go +++ b/internal/query/test/test_test.go @@ -5,7 +5,6 @@ import ( "testing" "queryorchestration/internal/collector" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/document" "queryorchestration/internal/query" @@ -16,7 +15,6 @@ import ( "github.com/stretchr/testify/require" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/assert" ) @@ -48,18 +46,18 @@ func TestTest(t *testing.T) { QueryVersion: int32(1), } - reqID := database.MustToDBUUID(uuid.New()) - pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(database.MustToDBUUID(params.QueryID), ¶ms.QueryVersion).WillReturnRows( + reqID := uuid.New() + pool.ExpectQuery("name: GetQueryWithVersion :one").WithArgs(¶ms.QueryID, ¶ms.QueryVersion).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(params.QueryID), repository.QuerytypeJsonExtractor, int32(1), params.QueryVersion+1, []byte("{\"path\":\"oldkey\"}"), []pgtype.UUID{reqID}), + AddRow(params.QueryID, repository.QuerytypeJsonExtractor, int32(1), params.QueryVersion+1, []byte("{\"path\":\"oldkey\"}"), []uuid.UUID{reqID}), ) strVal := "{\"mykey\":\"example_value\",\"oldkey\":\"old_value\"}" - pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(database.MustToDBUUID(params.QueryID), ¶ms.QueryVersion, database.MustToDBUUID(params.DocumentID)). + pool.ExpectQuery("name: ListQueryRequirementValues :many").WithArgs(¶ms.QueryID, ¶ms.QueryVersion, ¶ms.DocumentID). WillReturnRows( pgxmock.NewRows([]string{"id", "queryId", "type", "value"}). - AddRow(database.MustToDBUUID(uuid.New()), reqID, repository.QuerytypeContextFull, &strVal), + AddRow(&uuid.UUID{}, reqID, repository.QuerytypeContextFull, &strVal), ) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(params.QueryID)).WillReturnRows( + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(params.QueryID).WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte("{\"path\":\"oldkey\"}")), ) diff --git a/internal/query/types/jsonExtractor/process_test.go b/internal/query/types/jsonExtractor/process_test.go index 30fd8915..c65d1af9 100644 --- a/internal/query/types/jsonExtractor/process_test.go +++ b/internal/query/types/jsonExtractor/process_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" resultprocessor "queryorchestration/internal/query/result/processor" contextfull "queryorchestration/internal/query/types/contextFull" @@ -44,7 +43,7 @@ func TestJSONProcess(t *testing.T) { config := "{\"path\":\"key\"}" - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -59,7 +58,7 @@ func TestJSONProcess(t *testing.T) { values = []resultprocessor.Value{ contextfull.NewResult(jsonString), } - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -74,7 +73,7 @@ func TestJSONProcess(t *testing.T) { values = []resultprocessor.Value{ contextfull.NewResult(jsonString), } - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -110,7 +109,7 @@ func TestJSONProcessJSON(t *testing.T) { config := "{\"path\":\"invalid_key\"}" - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -122,7 +121,7 @@ func TestJSONProcessJSON(t *testing.T) { config = "" - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -134,7 +133,7 @@ func TestJSONProcessJSON(t *testing.T) { config = "{\"path\":\"\"}" - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -146,7 +145,7 @@ func TestJSONProcessJSON(t *testing.T) { config = "{\"path\":}" - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}). AddRow([]byte(config)), @@ -156,7 +155,7 @@ func TestJSONProcessJSON(t *testing.T) { assert.EqualError(t, err, "invalid character '}' looking for beginning of value") assert.Empty(t, value) - pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(database.MustToDBUUID(query.ID)). + pool.ExpectQuery("name: GetActiveQueryConfig :one").WithArgs(query.ID). WillReturnRows( pgxmock.NewRows([]string{"config"}), ) diff --git a/internal/query/types/jsonExtractor/service.go b/internal/query/types/jsonExtractor/service.go index 7ce90dba..840174e7 100644 --- a/internal/query/types/jsonExtractor/service.go +++ b/internal/query/types/jsonExtractor/service.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" - "queryorchestration/internal/database" resultprocessor "queryorchestration/internal/query/result/processor" "queryorchestration/internal/serviceconfig" @@ -34,7 +33,7 @@ func (e *Extractor) Process(ctx context.Context, query *resultprocessor.Query, v return "", err } - byteConfig, err := e.cfg.GetDBQueries().GetActiveQueryConfig(ctx, database.MustToDBUUID(query.ID)) + byteConfig, err := e.cfg.GetDBQueries().GetActiveQueryConfig(ctx, query.ID) if err != nil { return "", err } diff --git a/internal/query/update/update.go b/internal/query/update/update.go index 9db7ca22..1a0c47e9 100644 --- a/internal/query/update/update.go +++ b/internal/query/update/update.go @@ -7,7 +7,6 @@ import ( "log/slog" queryversionsyncrunner "queryorchestration/api/queryVersionSyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -67,8 +66,8 @@ func (s *Service) normalizeUpdateRequiredQueryIDs(ctx context.Context, current * } createsloop, err := s.cfg.GetDBQueries().IsQueryInDependencyTree(ctx, &repository.IsQueryInDependencyTreeParams{ - Queryid: database.MustToDBUUID(current.ID), - Requiredqueryids: database.MustToDBUUIDArray(*entity.GetRequiredQueryIDs()), + Queryid: ¤t.ID, + Requiredqueryids: *entity.GetRequiredQueryIDs(), }) if err != nil { return err @@ -127,7 +126,7 @@ func (s *Service) normalizeUpdate(ctx context.Context, current *query.Query, ent func (s *Service) submitUpdate(ctx context.Context, current *query.Query, entity *resultprocessor.Update) error { err := s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error { - id := database.MustToDBUUID(entity.ID) + id := entity.ID activeName, err := validation.GetFieldName(entity, entity.ActiveVersion) if err != nil { @@ -158,7 +157,7 @@ func (s *Service) submitUpdate(ctx context.Context, current *query.Query, entity for _, qID := range addIDs { err := q.AddRequiredQuery(ctx, &repository.AddRequiredQueryParams{ Queryid: id, - Requiredqueryid: database.MustToDBUUID(qID), + Requiredqueryid: qID, Addedversion: latestVersion, }) if err != nil { @@ -170,7 +169,7 @@ func (s *Service) submitUpdate(ctx context.Context, current *query.Query, entity for _, qID := range removeIDs { err := q.RemoveRequiredQuery(ctx, &repository.RemoveRequiredQueryParams{ Queryid: id, - Requiredqueryid: database.MustToDBUUID(qID), + Requiredqueryid: qID, Removedversion: &latestVersion, }) if err != nil { diff --git a/internal/query/update/update_test.go b/internal/query/update/update_test.go index bca3d787..ccf2f475 100644 --- a/internal/query/update/update_test.go +++ b/internal/query/update/update_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -19,7 +18,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/google/uuid" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v3" "github.com/stretchr/testify/mock" ) @@ -58,18 +56,18 @@ func TestUpdate(t *testing.T) { Config: &jcfg, } - pool.ExpectQuery("name: GetQuery :one").WithArgs(database.MustToDBUUID(update.ID)).WillReturnRows( + pool.ExpectQuery("name: GetQuery :one").WithArgs(update.ID).WillReturnRows( pgxmock.NewRows([]string{"id", "type", "activeVersion", "latestVersion", "config", "requiredIds"}). - AddRow(database.MustToDBUUID(existing.ID), repository.QuerytypeJsonExtractor, existing.ActiveVersion, existing.LatestVersion, []byte(config), []pgtype.UUID{}), + AddRow(existing.ID, repository.QuerytypeJsonExtractor, existing.ActiveVersion, existing.LatestVersion, []byte(config), []uuid.UUID{}), ) pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(update.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(update.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(2)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(update.ID), av). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(update.ID, av). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(database.MustToDBUUID(update.ID), []byte(*update.Config), int32(2)). + pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(update.ID, []byte(*update.Config), int32(2)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() diff --git a/internal/query/update/updateprivate_test.go b/internal/query/update/updateprivate_test.go index 1548160f..1dc2d98b 100644 --- a/internal/query/update/updateprivate_test.go +++ b/internal/query/update/updateprivate_test.go @@ -6,7 +6,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/query" resultprocessor "queryorchestration/internal/query/result/processor" @@ -87,17 +86,17 @@ func TestSubmitUpdate(t *testing.T) { } pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(q.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(q.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(3)), ) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), aV). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, aV). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(database.MustToDBUUID(update.ID), database.MustToDBUUID((*update.RequiredQueryIDs)[0]), pgxmock.AnyArg()). + pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(update.ID, (*update.RequiredQueryIDs)[0], pgxmock.AnyArg()). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), database.MustToDBUUID((*q.RequiredQueryIDs)[0]), database.MustToDBUUID(update.ID)). + pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), (*q.RequiredQueryIDs)[0], update.ID). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(database.MustToDBUUID(update.ID), []byte(*update.Config), int32(3)). + pool.ExpectExec("name: SetQueryConfig :exec").WithArgs(update.ID, []byte(*update.Config), int32(3)). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -130,7 +129,7 @@ func TestSubmitUpdateRollback(t *testing.T) { pool.ExpectBeginTx(pgx.TxOptions{}) msg := "database failure" - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), aV). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, aV). WillReturnError(errors.New(msg)) pool.ExpectCommit() @@ -174,17 +173,17 @@ func TestSubmitUpdateRequiredQueries(t *testing.T) { } pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(database.MustToDBUUID(update.ID)).WillReturnRows( + pool.ExpectQuery("name: AddLatestQueryVersion :one").WithArgs(update.ID).WillReturnRows( pgxmock.NewRows([]string{"version"}). AddRow(int32(1)), ) - pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(database.MustToDBUUID(update.ID), database.MustToDBUUID((*update.RequiredQueryIDs)[0]), pgxmock.AnyArg()). + pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(update.ID, (*update.RequiredQueryIDs)[0], pgxmock.AnyArg()). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(database.MustToDBUUID(update.ID), database.MustToDBUUID((*update.RequiredQueryIDs)[1]), pgxmock.AnyArg()). + pool.ExpectExec("name: AddRequiredQuery :exec").WithArgs(update.ID, (*update.RequiredQueryIDs)[1], pgxmock.AnyArg()). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), database.MustToDBUUID((*q.RequiredQueryIDs)[1]), database.MustToDBUUID(update.ID)). + pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), (*q.RequiredQueryIDs)[1], update.ID). WillReturnResult(pgxmock.NewResult("", 1)) - pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), database.MustToDBUUID((*q.RequiredQueryIDs)[2]), database.MustToDBUUID(update.ID)). + pool.ExpectExec("name: RemoveRequiredQuery :exec").WithArgs(pgxmock.AnyArg(), (*q.RequiredQueryIDs)[2], update.ID). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -223,7 +222,7 @@ func TestSubmitUpdateRequiredQueries(t *testing.T) { } pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), av). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, av). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -256,7 +255,7 @@ func TestSubmitUpdateActiveVersion(t *testing.T) { } pool.ExpectBeginTx(pgx.TxOptions{}) - pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(database.MustToDBUUID(q.ID), aV). + pool.ExpectExec("name: AddActiveQueryVersion :exec").WithArgs(q.ID, aV). WillReturnResult(pgxmock.NewResult("", 1)) pool.ExpectCommit() @@ -444,7 +443,7 @@ func TestNormalizeUpdateRequiredQueryIDs(t *testing.T) { ID: current.ID, RequiredQueryIDs: &[]uuid.UUID{uuid.New()}, } - dbids := database.MustToDBUUIDArray(*update.RequiredQueryIDs) + dbids := *update.RequiredQueryIDs pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). @@ -475,12 +474,12 @@ func TestNormalizeUpdateRequiredQueryIDs(t *testing.T) { RequiredQueryIDs: &[]uuid.UUID{uuid.New()}, } - dbids := database.MustToDBUUIDArray(*update.RequiredQueryIDs) + dbids := *update.RequiredQueryIDs pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) - pool.ExpectQuery("name: IsQueryInDependencyTree :one").WithArgs(dbids, database.MustToDBUUID(current.ID)).WillReturnRows( + pool.ExpectQuery("name: IsQueryInDependencyTree :one").WithArgs(dbids, current.ID).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) @@ -510,12 +509,12 @@ func TestNormalizeUpdateRequiredQueryIDs(t *testing.T) { update.RequiredQueryIDs = &ids current.RequiredQueryIDs = &ids - dbids := database.MustToDBUUIDArray(*update.RequiredQueryIDs) + dbids := *update.RequiredQueryIDs pool.ExpectQuery("name: AllQueriesExist :one").WithArgs(dbids).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(true), ) - pool.ExpectQuery("name: IsQueryInDependencyTree :one").WithArgs(dbids, database.MustToDBUUID(current.ID)).WillReturnRows( + pool.ExpectQuery("name: IsQueryInDependencyTree :one").WithArgs(dbids, ¤t.ID).WillReturnRows( pgxmock.NewRows([]string{"all_exist"}). AddRow(false), ) diff --git a/internal/query/versionsync/sync.go b/internal/query/versionsync/sync.go index 7e85c939..0149c9d7 100644 --- a/internal/query/versionsync/sync.go +++ b/internal/query/versionsync/sync.go @@ -6,14 +6,13 @@ import ( "errors" clientsyncrunner "queryorchestration/api/clientSyncRunner" - "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig/queue" "github.com/google/uuid" ) func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { - clientIds, err := s.cfg.GetDBQueries().ListQueryClientIDs(ctx, database.MustToDBUUID(id)) + clientIds, err := s.cfg.GetDBQueries().ListQueryClientIDs(ctx, &id) if err != nil && errors.Is(err, sql.ErrNoRows) { return nil } else if err != nil { @@ -24,7 +23,7 @@ func (s *Service) Sync(ctx context.Context, id uuid.UUID) error { err := s.cfg.SendToQueue(ctx, &queue.SendParams{ QueueURL: s.cfg.GetClientSyncURL(), Body: clientsyncrunner.Body{ - ID: database.MustToUUID(id), + ID: id, }, }) if err != nil { diff --git a/internal/query/versionsync/sync_test.go b/internal/query/versionsync/sync_test.go index c2851e31..19b1934c 100644 --- a/internal/query/versionsync/sync_test.go +++ b/internal/query/versionsync/sync_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/queue/clientsync" @@ -44,11 +43,11 @@ func TestSync(t *testing.T) { uuid.New(), } - pool.ExpectQuery("name: ListQueryClientIDs :many").WithArgs(database.MustToDBUUID(queryId)). + pool.ExpectQuery("name: ListQueryClientIDs :many").WithArgs(&queryId). WillReturnRows( pgxmock.NewRows([]string{"clientId"}). - AddRow(database.MustToDBUUID(clientIds[0])). - AddRow(database.MustToDBUUID(clientIds[1])), + AddRow(clientIds[0]). + AddRow(clientIds[1]), ) mockSQS.EXPECT(). diff --git a/internal/server/api/listener_test.go b/internal/server/api/listener_test.go index f95c9e1c..3b04f384 100644 --- a/internal/server/api/listener_test.go +++ b/internal/server/api/listener_test.go @@ -5,8 +5,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" - "path" "strings" "testing" @@ -28,7 +26,6 @@ func TestNew(t *testing.T) { cfg := &BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, }) diff --git a/internal/server/runner/listener_test.go b/internal/server/runner/listener_test.go index ff9c779d..7e0ff14e 100644 --- a/internal/server/runner/listener_test.go +++ b/internal/server/runner/listener_test.go @@ -2,8 +2,6 @@ package runner import ( "context" - "os" - "path" "testing" "time" @@ -24,7 +22,6 @@ func TestNew(t *testing.T) { ctx := context.Background() cfg := &BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, acleanup := test.CreateAWSContainer(t, ctx, &test.CreateAWSConfig{ Cfg: cfg, diff --git a/internal/server/server.go b/internal/server/server.go index e6347942..b8e03347 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -3,9 +3,9 @@ package server import ( "context" + "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig/build" - "queryorchestration/internal/database/migrations" "queryorchestration/internal/serviceconfig" "github.com/go-playground/validator/v10" @@ -46,7 +46,7 @@ func New(ctx context.Context, cfg Config) (func() error, error) { version := build.GetVersion() cfg.GetLogger().Info("Starting", "version", version) - err := migrations.Run(ctx, cfg) + err := database.RunMigrations(ctx, cfg) if err != nil { return func() error { return nil }, err } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 08e63e97..d72e2081 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -3,8 +3,6 @@ package server_test import ( "context" "fmt" - "os" - "path" "testing" "queryorchestration/internal/server" @@ -23,7 +21,6 @@ func TestNew(t *testing.T) { cfg := &server.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, diff --git a/internal/serviceconfig/common.go b/internal/serviceconfig/common.go index 893f0dd5..e7fe2f1a 100644 --- a/internal/serviceconfig/common.go +++ b/internal/serviceconfig/common.go @@ -31,11 +31,7 @@ type BaseConfig struct { // Always place non struct fields at the top of the struct // this is a requirement for the PrintAuthConfig function. - // miscellaneous fields uncategorized - // PWD will replace the BASE_PATH env var Pwd string `env:"PWD,required,notEmpty"` - // BASE_PATH will override the PWD env var if present - BasePath string `env:"BASE_PATH"` rbac.AuthConfig logger.LogConfig @@ -57,8 +53,6 @@ type ConfigProvider interface { aws.ConfigProvider queue.ConfigProvider rbac.ConfigProvider - GetBasePath() string - SetBasePath(string) SetDBConfig(*database.DBConfig) SetAWSConfig(*aws.AWSConfig) } @@ -169,17 +163,6 @@ func initializeConfigPrivate(cfg ConfigProvider) error { return initErr } -func (b *BaseConfig) GetBasePath() string { - if b.BasePath != "" { - return b.BasePath - } - return b.Pwd -} - -func (b *BaseConfig) SetBasePath(p string) { - b.BasePath = p -} - func (b *BaseConfig) SetDBConfig(cfg *database.DBConfig) { b.DBConfig = *cfg } diff --git a/internal/serviceconfig/common_test.go b/internal/serviceconfig/common_test.go index 81f89ca1..1527d0ae 100644 --- a/internal/serviceconfig/common_test.go +++ b/internal/serviceconfig/common_test.go @@ -149,21 +149,6 @@ func TestGetBaseConfig(t *testing.T) { os.Clearenv() } -func TestGetBasePath(t *testing.T) { - cfg := &BaseConfig{ - Pwd: "pwd_path", - } - assert.Equal(t, "pwd_path", cfg.GetBasePath()) - cfg.SetBasePath("base_path") - assert.Equal(t, "base_path", cfg.GetBasePath()) -} - -func TestSetBasePath(t *testing.T) { - cfg := &BaseConfig{} - cfg.SetBasePath("/i/am/here") - assert.Equal(t, "/i/am/here", cfg.BasePath) -} - func TestSetDBConfig(t *testing.T) { cfg := &BaseConfig{} dbcfg := database.DBConfig{ diff --git a/internal/serviceconfig/config.diagram.md b/internal/serviceconfig/config.diagram.md index 686bc0d2..de17b4db 100644 --- a/internal/serviceconfig/config.diagram.md +++ b/internal/serviceconfig/config.diagram.md @@ -23,8 +23,6 @@ class BaseConfig["serviceconfig.BaseConfig"] { +ObservabilityConfig +database.BaseConfig +Pwd string -+BasePath string -+GetBasePath() +GetLogger() +LogConfig() } @@ -32,7 +30,6 @@ class ConfigProvider["serviceconfig.ConfigProvider"] { <> +database.ConfigProvider +ObservabilityConfigProvider -+GetBasePath() +GetLogger() +LogConfig() } diff --git a/internal/serviceconfig/database/pool_test.go b/internal/serviceconfig/database/pool_test.go index b299ec8c..6c073d1d 100644 --- a/internal/serviceconfig/database/pool_test.go +++ b/internal/serviceconfig/database/pool_test.go @@ -2,8 +2,6 @@ package database_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/database/repository" @@ -24,7 +22,6 @@ func TestSetDBPool(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../../..")) _, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, RunMigrations: true, diff --git a/internal/serviceconfig/database/transaction_test.go b/internal/serviceconfig/database/transaction_test.go index 214afc2d..eae26936 100644 --- a/internal/serviceconfig/database/transaction_test.go +++ b/internal/serviceconfig/database/transaction_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "queryorchestration/internal/database" "queryorchestration/internal/database/repository" "queryorchestration/internal/serviceconfig" @@ -23,7 +22,7 @@ func TestExecuteTransaction(t *testing.T) { cfg.DBPool = pool cfg.DBQueries = repository.New(pool) - clientID := database.MustToDBUUID(uuid.New()) + clientID := uuid.New() clientName := "example_client" externalId := "example_id" diff --git a/internal/serviceconfig/textract/client.go b/internal/serviceconfig/textract/client.go new file mode 100644 index 00000000..3472df8b --- /dev/null +++ b/internal/serviceconfig/textract/client.go @@ -0,0 +1,36 @@ +package textract + +import ( + "context" + + "github.com/aws/aws-sdk-go-v2/service/textract" +) + +type TextractClient interface { + // Document Analysis Operations + AnalyzeDocument(ctx context.Context, params *textract.AnalyzeDocumentInput, opts ...func(*textract.Options)) (*textract.AnalyzeDocumentOutput, error) + DetectDocumentText(ctx context.Context, params *textract.DetectDocumentTextInput, opts ...func(*textract.Options)) (*textract.DetectDocumentTextOutput, error) + AnalyzeExpense(ctx context.Context, params *textract.AnalyzeExpenseInput, opts ...func(*textract.Options)) (*textract.AnalyzeExpenseOutput, error) + AnalyzeID(ctx context.Context, params *textract.AnalyzeIDInput, opts ...func(*textract.Options)) (*textract.AnalyzeIDOutput, error) + + // Asynchronous Operations + StartDocumentAnalysis(ctx context.Context, params *textract.StartDocumentAnalysisInput, opts ...func(*textract.Options)) (*textract.StartDocumentAnalysisOutput, error) + StartDocumentTextDetection(ctx context.Context, params *textract.StartDocumentTextDetectionInput, opts ...func(*textract.Options)) (*textract.StartDocumentTextDetectionOutput, error) + StartExpenseAnalysis(ctx context.Context, params *textract.StartExpenseAnalysisInput, opts ...func(*textract.Options)) (*textract.StartExpenseAnalysisOutput, error) + + // Job Management Operations + GetDocumentAnalysis(ctx context.Context, params *textract.GetDocumentAnalysisInput, opts ...func(*textract.Options)) (*textract.GetDocumentAnalysisOutput, error) + GetDocumentTextDetection(ctx context.Context, params *textract.GetDocumentTextDetectionInput, opts ...func(*textract.Options)) (*textract.GetDocumentTextDetectionOutput, error) + GetExpenseAnalysis(ctx context.Context, params *textract.GetExpenseAnalysisInput, opts ...func(*textract.Options)) (*textract.GetExpenseAnalysisOutput, error) + + // Adapting Operations + CreateAdapterVersion(ctx context.Context, params *textract.CreateAdapterVersionInput, opts ...func(*textract.Options)) (*textract.CreateAdapterVersionOutput, error) + DeleteAdapter(ctx context.Context, params *textract.DeleteAdapterInput, opts ...func(*textract.Options)) (*textract.DeleteAdapterOutput, error) + GetAdapter(ctx context.Context, params *textract.GetAdapterInput, opts ...func(*textract.Options)) (*textract.GetAdapterOutput, error) + GetAdapterVersion(ctx context.Context, params *textract.GetAdapterVersionInput, opts ...func(*textract.Options)) (*textract.GetAdapterVersionOutput, error) + ListAdapters(ctx context.Context, params *textract.ListAdaptersInput, opts ...func(*textract.Options)) (*textract.ListAdaptersOutput, error) + UpdateAdapter(ctx context.Context, params *textract.UpdateAdapterInput, opts ...func(*textract.Options)) (*textract.UpdateAdapterOutput, error) + + // Query-based Analysis + CreateAdapter(ctx context.Context, params *textract.CreateAdapterInput, opts ...func(*textract.Options)) (*textract.CreateAdapterOutput, error) +} diff --git a/internal/serviceconfig/textract/config.go b/internal/serviceconfig/textract/config.go new file mode 100644 index 00000000..2b9d1dc9 --- /dev/null +++ b/internal/serviceconfig/textract/config.go @@ -0,0 +1,47 @@ +package textract + +import ( + "context" + "fmt" + + awsc "queryorchestration/internal/serviceconfig/aws" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/textract" +) + +type ConfigProvider interface { + awsc.ConfigProvider + SetTextractClient(context.Context) error + GetTextractClient() TextractClient + SetTextractEndpoint(string) + GetTextractEndpoint() string +} + +type TextractConfig struct { + AWSEndpointUrlTextract string `env:"AWS_ENDPOINT_URL_TEXTRACT"` + TextractClient TextractClient +} + +func (c *TextractConfig) SetTextractClient(ctx context.Context) error { + cfg, err := config.LoadDefaultConfig(ctx) + if err != nil { + return fmt.Errorf("unable to load SDK config: %v", err) + } + + c.TextractClient = textract.NewFromConfig(cfg) + + return nil +} + +func (c *TextractConfig) GetTextractClient() TextractClient { + return c.TextractClient +} + +func (c *TextractConfig) GetTextractEndpoint() string { + return c.AWSEndpointUrlTextract +} + +func (c *TextractConfig) SetTextractEndpoint(e string) { + c.AWSEndpointUrlTextract = e +} diff --git a/internal/serviceconfig/textract/config_test.go b/internal/serviceconfig/textract/config_test.go new file mode 100644 index 00000000..2ec6c4e6 --- /dev/null +++ b/internal/serviceconfig/textract/config_test.go @@ -0,0 +1,43 @@ +package textract_test + +import ( + "context" + "os" + "testing" + + textract "queryorchestration/internal/serviceconfig/textract" + + awstextract "github.com/aws/aws-sdk-go-v2/service/textract" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetTextractClient(t *testing.T) { + c := textract.TextractConfig{} + assert.Nil(t, c.GetTextractClient()) + c.TextractClient = &awstextract.Client{} + assert.Equal(t, &awstextract.Client{}, c.GetTextractClient()) +} + +func TestTextractClient(t *testing.T) { + os.Clearenv() + ctx := context.Background() + c := textract.TextractConfig{} + err := c.SetTextractClient(ctx) + require.NoError(t, err) + assert.NotNil(t, c.TextractClient) +} + +func TestGetTextractURL(t *testing.T) { + c := textract.TextractConfig{} + assert.Empty(t, c.GetTextractEndpoint()) + c.AWSEndpointUrlTextract = "textract_endpoint" + assert.Equal(t, "textract_endpoint", c.GetTextractEndpoint()) +} + +func TestSetTextractURL(t *testing.T) { + os.Clearenv() + c := textract.TextractConfig{} + c.SetTextractEndpoint("example") + assert.Equal(t, "example", c.AWSEndpointUrlTextract) +} diff --git a/internal/test/api_test.go b/internal/test/api_test.go index 08663023..88cde72a 100644 --- a/internal/test/api_test.go +++ b/internal/test/api_test.go @@ -2,8 +2,6 @@ package test_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/serviceconfig" @@ -23,7 +21,6 @@ func TestCreateAPI(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../..")) _, dbcleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Network: ncfg, Cfg: cfg, diff --git a/internal/test/database.go b/internal/test/database.go index e0f19077..835e085a 100644 --- a/internal/test/database.go +++ b/internal/test/database.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "queryorchestration/internal/database/migrations" + db "queryorchestration/internal/database" "queryorchestration/internal/serviceconfig" "queryorchestration/internal/serviceconfig/database" @@ -94,7 +94,7 @@ func CreateDB(t testing.TB, ctx context.Context, cfg *CreateDatabaseConfig) (tes cfg.Cfg.SetDBConfig(dbcfg) if cfg.RunMigrations { - err := migrations.Run(ctx, cfg.Cfg) + err := db.RunMigrations(ctx, cfg.Cfg) require.NoError(t, err) err = cfg.Cfg.SetDBPool(ctx) diff --git a/internal/test/database_test.go b/internal/test/database_test.go index 6d39bb8b..8e362acf 100644 --- a/internal/test/database_test.go +++ b/internal/test/database_test.go @@ -2,8 +2,6 @@ package test_test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/serviceconfig" @@ -20,7 +18,6 @@ func TestCreateDB(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../..")) dbcfg, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{Cfg: cfg}) assert.NotNil(t, dbcfg) @@ -38,7 +35,6 @@ func TestCreateDBWithMigrations(t *testing.T) { cfg := &serviceconfig.BaseConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../..")) dbcfg, cleanup := test.CreateDB(t, ctx, &test.CreateDatabaseConfig{ Cfg: cfg, diff --git a/internal/test/ecosystem.go b/internal/test/ecosystem.go index b76a8583..f7a8c155 100644 --- a/internal/test/ecosystem.go +++ b/internal/test/ecosystem.go @@ -2,8 +2,6 @@ package test import ( "context" - "os" - "path" "testing" "queryorchestration/internal/serviceconfig" @@ -121,12 +119,6 @@ func CreateFullDependencies(t testing.TB, ctx context.Context, cfg FullDependenc } } -func SetCfgProviderWithBasePath(t testing.TB, cfg serviceconfig.ConfigProvider, basePath string) { - SetCfgProvider(t, cfg) - - cfg.SetBasePath(path.Join(os.Getenv("PWD"), basePath)) -} - func SetCfgProvider(t testing.TB, cfg serviceconfig.ConfigProvider) { cfg.SetAWSConfig(&aws.AWSConfig{ AWSKeyID: "test", diff --git a/internal/test/ecosystem_test.go b/internal/test/ecosystem_test.go index 758f7033..cb4d233a 100644 --- a/internal/test/ecosystem_test.go +++ b/internal/test/ecosystem_test.go @@ -51,7 +51,7 @@ func TestCreateFullDependencies(t *testing.T) { } ctx := context.Background() cfg := &FullDepsConfig{} - SetCfgProviderWithBasePath(t, cfg, "../..") + SetCfgProvider(t, cfg) conn, cleanup := CreateFullDependencies(t, ctx, cfg) @@ -67,7 +67,7 @@ func TestCreateNetwork(t *testing.T) { } ctx := context.Background() cfg := &FullDepsConfig{} - SetCfgProviderWithBasePath(t, cfg, "../..") + SetCfgProvider(t, cfg) conn, cleanup := CreateFullNetwork(t, ctx, cfg) diff --git a/scripts/database.yml b/scripts/database.yml index 8dc2ff46..b6dc350a 100644 --- a/scripts/database.yml +++ b/scripts/database.yml @@ -4,7 +4,7 @@ version: "3" vars: - MIGRATIONS: "database/migrations" + MIGRATIONS: "internal/database/migrations" tasks: generate: @@ -23,7 +23,7 @@ tasks: - sqlc vet --file sqlc.yml - | exit 0 - for file in database/migrations/*.sql; do + for file in internal/database/migrations/*.sql; do if [[ -f "$file" ]]; then sqlcheck -c -f $file -r 3 # move to 1 fi diff --git a/sqlc.yml b/sqlc.yml index 580440a5..9b3910a5 100644 --- a/sqlc.yml +++ b/sqlc.yml @@ -6,8 +6,8 @@ servers: sql: - name: "db" engine: "postgresql" - queries: "database/queries/" - schema: "database/migrations" + queries: "internal/database/queries/" + schema: "internal/database/migrations" rules: - sqlc/db-prepare - no-delete @@ -28,6 +28,17 @@ sql: emit_params_struct_pointers: true emit_enum_valid_method: true emit_sql_as_comment: true + overrides: + - db_type: "uuid" + go_type: + import: "github.com/google/uuid" + type: "UUID" + - db_type: "uuid" + nullable: true + go_type: + import: "github.com/google/uuid" + type: "UUID" + pointer: true rules: - name: no-pg message: "invalid engine: not postgresql" diff --git a/test/process_test.go b/test/process_test.go index 8c55b4d3..14a84213 100644 --- a/test/process_test.go +++ b/test/process_test.go @@ -26,7 +26,7 @@ func TestProcess(t *testing.T) { ctx := context.Background() cfg := &ProcessConfig{} - test.SetCfgProviderWithBasePath(t, cfg, "..") + test.SetCfgProvider(t, cfg) net, clean := test.CreateFullNetwork(t, ctx, cfg) defer clean() diff --git a/test/queryAPI/collectorservice_test.go b/test/queryAPI/collectorservice_test.go index 9dc74548..9e6a229a 100644 --- a/test/queryAPI/collectorservice_test.go +++ b/test/queryAPI/collectorservice_test.go @@ -25,7 +25,7 @@ func TestCollectorService(t *testing.T) { ctx := context.Background() cfg := &CollectorConfig{} - test.SetCfgProviderWithBasePath(t, cfg, "../..") + test.SetCfgProvider(t, cfg) network, ncleanup := test.CreateNetwork(t, ctx) defer ncleanup() diff --git a/test/queryAPI/queryservice_test.go b/test/queryAPI/queryservice_test.go index c5c89cfd..0efe6109 100644 --- a/test/queryAPI/queryservice_test.go +++ b/test/queryAPI/queryservice_test.go @@ -2,8 +2,6 @@ package endtoend_test import ( "context" - "os" - "path" "regexp" "testing" @@ -28,7 +26,6 @@ func TestQueryAPI(t *testing.T) { cfg := &QueryConfig{} test.SetCfgProvider(t, cfg) - cfg.SetBasePath(path.Join(os.Getenv("PWD"), "../..")) network, ncleanup := test.CreateNetwork(t, ctx) defer ncleanup() diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/CHANGELOG.md new file mode 100644 index 00000000..9cf13d0f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/CHANGELOG.md @@ -0,0 +1,596 @@ +# v1.35.1 (2025-03-04.2) + +* **Bug Fix**: Add assurance test for operation order. + +# v1.35.0 (2025-02-27) + +* **Feature**: Track credential providers via User-Agent Feature ids +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.19 (2025-02-18) + +* **Bug Fix**: Bump go version to 1.22 +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.18 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.17 (2025-02-04) + +* No change notes available for this release. + +# v1.34.16 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.15 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.14 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.34.13 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.34.12 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.11 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.10 (2024-12-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.9 (2024-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.8 (2024-11-18) + +* **Dependency Update**: Update to smithy-go v1.22.1. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.7 (2024-11-07) + +* **Bug Fix**: Adds case-insensitive handling of error message fields in service responses + +# v1.34.6 (2024-11-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.5 (2024-10-31) + +* No change notes available for this release. + +# v1.34.4 (2024-10-29) + +* No change notes available for this release. + +# v1.34.3 (2024-10-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.2 (2024-10-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.1 (2024-10-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.0 (2024-10-04) + +* **Feature**: Add support for HTTP client metrics. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.4 (2024-10-03) + +* No change notes available for this release. + +# v1.33.3 (2024-09-27) + +* No change notes available for this release. + +# v1.33.2 (2024-09-25) + +* No change notes available for this release. + +# v1.33.1 (2024-09-23) + +* No change notes available for this release. + +# v1.33.0 (2024-09-20) + +* **Feature**: Add tracing and metrics support to service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.7 (2024-09-17) + +* **Bug Fix**: **BREAKFIX**: Only generate AccountIDEndpointMode config for services that use it. This is a compiler break, but removes no actual functionality, as no services currently use the account ID in endpoint resolution. + +# v1.32.6 (2024-09-04) + +* No change notes available for this release. + +# v1.32.5 (2024-09-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.4 (2024-08-15) + +* **Dependency Update**: Bump minimum Go version to 1.21. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.3 (2024-07-10.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.2 (2024-07-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.1 (2024-06-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.0 (2024-06-26) + +* **Feature**: Support list-of-string endpoint parameter. + +# v1.31.1 (2024-06-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.0 (2024-06-18) + +* **Feature**: Track usage of various AWS SDK features in user-agent string. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.12 (2024-06-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.11 (2024-06-07) + +* **Bug Fix**: Add clock skew correction on all service clients +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.10 (2024-06-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.9 (2024-05-23) + +* No change notes available for this release. + +# v1.30.8 (2024-05-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.7 (2024-05-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.6 (2024-05-08) + +* **Bug Fix**: GoDoc improvement + +# v1.30.5 (2024-03-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.4 (2024-03-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.3 (2024-03-15) + +* No change notes available for this release. + +# v1.30.2 (2024-03-07) + +* **Bug Fix**: Remove dependency on go-cmp. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.1 (2024-02-23) + +* **Bug Fix**: Move all common, SDK-side middleware stack ops into the service client module to prevent cross-module compatibility issues in the future. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.0 (2024-02-22) + +* **Feature**: Add middleware stack snapshot tests. + +# v1.29.3 (2024-02-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.2 (2024-02-20) + +* **Bug Fix**: When sourcing values for a service's `EndpointParameters`, the lack of a configured region (i.e. `options.Region == ""`) will now translate to a `nil` value for `EndpointParameters.Region` instead of a pointer to the empty string `""`. This will result in a much more explicit error when calling an operation instead of an obscure hostname lookup failure. + +# v1.29.1 (2024-02-15) + +* **Bug Fix**: Correct failure to determine the error type in awsJson services that could occur when errors were modeled with a non-string `code` field. + +# v1.29.0 (2024-02-13) + +* **Feature**: Bump minimum Go version to 1.20 per our language support policy. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.6 (2024-01-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.5 (2023-12-08) + +* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. + +# v1.28.4 (2023-12-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.3 (2023-12-06) + +* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. + +# v1.28.2 (2023-12-01) + +* **Bug Fix**: Correct wrapping of errors in authentication workflow. +* **Bug Fix**: Correctly recognize cache-wrapped instances of AnonymousCredentials at client construction. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.1 (2023-11-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.0 (2023-11-29) + +* **Feature**: Expose Options() accessor on service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.5 (2023-11-28.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.4 (2023-11-28) + +* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. + +# v1.27.3 (2023-11-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.2 (2023-11-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.1 (2023-11-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.0 (2023-11-01) + +* **Feature**: Adds support for configured endpoints via environment variables and the AWS shared configuration file. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.26.0 (2023-10-31) + +* **Feature**: **BREAKING CHANGE**: Bump minimum go version to 1.19 per the revised [go version support policy](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-aligns-with-go-release-policy-on-supported-runtimes/). +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.0 (2023-10-12) + +* **Feature**: This release adds 9 new APIs for adapter and adapter version management, 3 new APIs for tagging, and updates AnalyzeDocument and StartDocumentAnalysis API parameters for using adapters. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.1 (2023-10-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.0 (2023-09-27) + +* **Feature**: This release adds new feature - Layout to Analyze Document API which can automatically extract layout elements such as titles, paragraphs, headers, section headers, lists, page numbers, footers, table areas, key-value areas and figure areas and order the elements as a human would read. + +# v1.23.0 (2023-09-18) + +* **Announcement**: [BREAKFIX] Change in MaxResults datatype from value to pointer type in cognito-sync service. +* **Feature**: Adds several endpoint ruleset changes across all models: smaller rulesets, removed non-unique regional endpoints, fixes FIPS and DualStack endpoints, and make region not required in SDK::Endpoint. Additional breakfix to cognito-sync field. + +# v1.22.5 (2023-08-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.4 (2023-08-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.3 (2023-08-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.2 (2023-08-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.1 (2023-08-01) + +* No change notes available for this release. + +# v1.22.0 (2023-07-31) + +* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.8 (2023-07-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.7 (2023-07-13) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.6 (2023-06-15) + +* No change notes available for this release. + +# v1.21.5 (2023-06-13) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.4 (2023-05-04) + +* No change notes available for this release. + +# v1.21.3 (2023-04-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.2 (2023-04-10) + +* No change notes available for this release. + +# v1.21.1 (2023-04-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.0 (2023-03-23) + +* **Feature**: The AnalyzeDocument - Tables feature adds support for new elements in the API: table titles, footers, section titles, summary cells/tables, and table type. + +# v1.20.6 (2023-03-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.5 (2023-03-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.4 (2023-02-22) + +* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. + +# v1.20.3 (2023-02-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.2 (2023-02-15) + +* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. +* **Bug Fix**: Correct error type parsing for restJson services. + +# v1.20.1 (2023-02-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.0 (2023-01-05) + +* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). + +# v1.19.2 (2022-12-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.1 (2022-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.0 (2022-11-28) + +* **Feature**: This release adds support for classifying and splitting lending documents by type, and extracting information by using the Analyze Lending APIs. This release also includes support for summarized information of the processed lending document package, in addition to per document results. + +# v1.18.0 (2022-11-17) + +* **Feature**: This release adds support for specifying and extracting information from documents using the Signatures feature within Analyze Document API + +# v1.17.0 (2022-11-01) + +* **Feature**: Add ocr results in AnalyzeIDResponse as blocks + +# v1.16.0 (2022-10-31) + +* **Feature**: This release introduces additional support for 30+ normalized fields such as vendor address and currency. It also includes OCR output in the response and accuracy improvements for the already supported fields in previous version + +# v1.15.16 (2022-10-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.15 (2022-10-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.14 (2022-09-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.13 (2022-09-14) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.12 (2022-09-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.11 (2022-08-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.10 (2022-08-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.9 (2022-08-11) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.8 (2022-08-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.7 (2022-08-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.6 (2022-08-01) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.5 (2022-07-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.4 (2022-06-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.3 (2022-06-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.2 (2022-05-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.1 (2022-04-25) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.0 (2022-04-19) + +* **Feature**: This release adds support for specifying and extracting information from documents using the Queries feature within Analyze Document API + +# v1.14.3 (2022-03-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.14.2 (2022-03-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.14.1 (2022-03-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.14.0 (2022-03-08) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.0 (2022-02-24) + +* **Feature**: API client updated +* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.0 (2022-01-14) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.11.0 (2022-01-07) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.10.1 (2021-12-02) + +* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.10.0 (2021-11-30) + +* **Feature**: API client updated + +# v1.9.1 (2021-11-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.9.0 (2021-11-12) + +* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. + +# v1.8.0 (2021-11-06) + +* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Feature**: Updated service to latest API model. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.7.0 (2021-10-21) + +* **Feature**: Updated to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.6.0 (2021-10-11) + +* **Feature**: API client updated +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.5.1 (2021-09-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.5.0 (2021-08-27) + +* **Feature**: Updated API model to latest revision. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.1 (2021-08-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.0 (2021-08-04) + +* **Feature**: Updated to latest API model. +* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.1 (2021-07-15) + +* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.0 (2021-06-25) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.2.1 (2021-05-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.2.0 (2021-05-14) + +* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. +* **Dependency Update**: Updated to the latest SDK module versions + diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/LICENSE.txt @@ -0,0 +1,202 @@ + + 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/aws/aws-sdk-go-v2/service/textract/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_client.go new file mode 100644 index 00000000..4f27811b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_client.go @@ -0,0 +1,959 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + cryptorand "crypto/rand" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/defaults" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + internalmiddleware "github.com/aws/aws-sdk-go-v2/internal/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + smithydocument "github.com/aws/smithy-go/document" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + smithyrand "github.com/aws/smithy-go/rand" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net" + "net/http" + "sync/atomic" + "time" +) + +const ServiceID = "Textract" +const ServiceAPIVersion = "2018-06-27" + +type operationMetrics struct { + Duration metrics.Float64Histogram + SerializeDuration metrics.Float64Histogram + ResolveIdentityDuration metrics.Float64Histogram + ResolveEndpointDuration metrics.Float64Histogram + SignRequestDuration metrics.Float64Histogram + DeserializeDuration metrics.Float64Histogram +} + +func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram { + switch name { + case "client.call.duration": + return m.Duration + case "client.call.serialization_duration": + return m.SerializeDuration + case "client.call.resolve_identity_duration": + return m.ResolveIdentityDuration + case "client.call.resolve_endpoint_duration": + return m.ResolveEndpointDuration + case "client.call.signing_duration": + return m.SignRequestDuration + case "client.call.deserialization_duration": + return m.DeserializeDuration + default: + panic("unrecognized operation metric") + } +} + +func timeOperationMetric[T any]( + ctx context.Context, metric string, fn func() (T, error), + opts ...metrics.RecordMetricOption, +) (T, error) { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + start := time.Now() + v, err := fn() + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + return v, err +} + +func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + var ended bool + start := time.Now() + return func() { + if ended { + return + } + ended = true + + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + } +} + +func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { + return func(o *metrics.RecordMetricOptions) { + o.Properties.Set("rpc.service", middleware.GetServiceID(ctx)) + o.Properties.Set("rpc.method", middleware.GetOperationName(ctx)) + } +} + +type operationMetricsKey struct{} + +func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/textract") + om := &operationMetrics{} + + var err error + + om.Duration, err = operationMetricTimer(meter, "client.call.duration", + "Overall call duration (including retries and time to send or receive request and response body)") + if err != nil { + return nil, err + } + om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration", + "The time it takes to serialize a message body") + if err != nil { + return nil, err + } + om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration", + "The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider") + if err != nil { + return nil, err + } + om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration", + "The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request") + if err != nil { + return nil, err + } + om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration", + "The time it takes to sign a request") + if err != nil { + return nil, err + } + om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration", + "The time it takes to deserialize a message body") + if err != nil { + return nil, err + } + + return context.WithValue(parent, operationMetricsKey{}, om), nil +} + +func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) { + return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) { + o.UnitLabel = "s" + o.Description = desc + }) +} + +func getOperationMetrics(ctx context.Context) *operationMetrics { + return ctx.Value(operationMetricsKey{}).(*operationMetrics) +} + +func operationTracer(p tracing.TracerProvider) tracing.Tracer { + return p.Tracer("github.com/aws/aws-sdk-go-v2/service/textract") +} + +// Client provides the API client to make operations call for Amazon Textract. +type Client struct { + options Options + + // Difference between the time reported by the server and the client + timeOffset *atomic.Int64 +} + +// New returns an initialized Client based on the functional options. Provide +// additional functional options to further configure the behavior of the client, +// such as changing the client's endpoint or adding custom middleware behavior. +func New(options Options, optFns ...func(*Options)) *Client { + options = options.Copy() + + resolveDefaultLogger(&options) + + setResolvedDefaultsMode(&options) + + resolveRetryer(&options) + + resolveHTTPClient(&options) + + resolveHTTPSignerV4(&options) + + resolveIdempotencyTokenProvider(&options) + + resolveEndpointResolverV2(&options) + + resolveTracerProvider(&options) + + resolveMeterProvider(&options) + + resolveAuthSchemeResolver(&options) + + for _, fn := range optFns { + fn(&options) + } + + finalizeRetryMaxAttempts(&options) + + ignoreAnonymousAuth(&options) + + wrapWithAnonymousAuth(&options) + + resolveAuthSchemes(&options) + + client := &Client{ + options: options, + } + + initializeTimeOffsetResolver(client) + + return client +} + +// Options returns a copy of the client configuration. +// +// Callers SHOULD NOT perform mutations on any inner structures within client +// config. Config overrides should instead be made on a per-operation basis through +// functional options. +func (c *Client) Options() Options { + return c.options.Copy() +} + +func (c *Client) invokeOperation( + ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error, +) ( + result interface{}, metadata middleware.Metadata, err error, +) { + ctx = middleware.ClearStackValues(ctx) + ctx = middleware.WithServiceID(ctx, ServiceID) + ctx = middleware.WithOperationName(ctx, opID) + + stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) + options := c.options.Copy() + + for _, fn := range optFns { + fn(&options) + } + + finalizeOperationRetryMaxAttempts(&options, *c) + + finalizeClientEndpointResolverOptions(&options) + + for _, fn := range stackFns { + if err := fn(stack, options); err != nil { + return nil, metadata, err + } + } + + for _, fn := range options.APIOptions { + if err := fn(stack); err != nil { + return nil, metadata, err + } + } + + ctx, err = withOperationMetrics(ctx, options.MeterProvider) + if err != nil { + return nil, metadata, err + } + + tracer := operationTracer(options.TracerProvider) + spanName := fmt.Sprintf("%s.%s", ServiceID, opID) + + ctx = tracing.WithOperationTracer(ctx, tracer) + + ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) { + o.Kind = tracing.SpanKindClient + o.Properties.Set("rpc.system", "aws-api") + o.Properties.Set("rpc.method", opID) + o.Properties.Set("rpc.service", ServiceID) + }) + endTimer := startMetricTimer(ctx, "client.call.duration") + defer endTimer() + defer span.End() + + handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) { + o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/textract") + }) + decorated := middleware.DecorateHandler(handler, stack) + result, metadata, err = decorated.Handle(ctx, params) + if err != nil { + span.SetProperty("exception.type", fmt.Sprintf("%T", err)) + span.SetProperty("exception.message", err.Error()) + + var aerr smithy.APIError + if errors.As(err, &aerr) { + span.SetProperty("api.error_code", aerr.ErrorCode()) + span.SetProperty("api.error_message", aerr.ErrorMessage()) + span.SetProperty("api.error_fault", aerr.ErrorFault().String()) + } + + err = &smithy.OperationError{ + ServiceID: ServiceID, + OperationName: opID, + Err: err, + } + } + + span.SetProperty("error", err != nil) + if err == nil { + span.SetStatus(tracing.SpanStatusOK) + } else { + span.SetStatus(tracing.SpanStatusError) + } + + return result, metadata, err +} + +type operationInputKey struct{} + +func setOperationInput(ctx context.Context, input interface{}) context.Context { + return middleware.WithStackValue(ctx, operationInputKey{}, input) +} + +func getOperationInput(ctx context.Context) interface{} { + return middleware.GetStackValue(ctx, operationInputKey{}) +} + +type setOperationInputMiddleware struct { +} + +func (*setOperationInputMiddleware) ID() string { + return "setOperationInput" +} + +func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + ctx = setOperationInput(ctx, in.Parameters) + return next.HandleSerialize(ctx, in) +} + +func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error { + if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil { + return fmt.Errorf("add ResolveAuthScheme: %w", err) + } + if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil { + return fmt.Errorf("add GetIdentity: %v", err) + } + if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { + return fmt.Errorf("add ResolveEndpointV2: %v", err) + } + if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil { + return fmt.Errorf("add Signing: %w", err) + } + return nil +} +func resolveAuthSchemeResolver(options *Options) { + if options.AuthSchemeResolver == nil { + options.AuthSchemeResolver = &defaultAuthSchemeResolver{} + } +} + +func resolveAuthSchemes(options *Options) { + if options.AuthSchemes == nil { + options.AuthSchemes = []smithyhttp.AuthScheme{ + internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{ + Signer: options.HTTPSignerV4, + Logger: options.Logger, + LogSigning: options.ClientLogMode.IsSigning(), + }), + } + } +} + +type noSmithyDocumentSerde = smithydocument.NoSerde + +type legacyEndpointContextSetter struct { + LegacyResolver EndpointResolver +} + +func (*legacyEndpointContextSetter) ID() string { + return "legacyEndpointContextSetter" +} + +func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + if m.LegacyResolver != nil { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) + } + + return next.HandleInitialize(ctx, in) + +} +func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { + return stack.Initialize.Add(&legacyEndpointContextSetter{ + LegacyResolver: o.EndpointResolver, + }, middleware.Before) +} + +func resolveDefaultLogger(o *Options) { + if o.Logger != nil { + return + } + o.Logger = logging.Nop{} +} + +func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { + return middleware.AddSetLoggerMiddleware(stack, o.Logger) +} + +func setResolvedDefaultsMode(o *Options) { + if len(o.resolvedDefaultsMode) > 0 { + return + } + + var mode aws.DefaultsMode + mode.SetFromString(string(o.DefaultsMode)) + + if mode == aws.DefaultsModeAuto { + mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) + } + + o.resolvedDefaultsMode = mode +} + +// NewFromConfig returns a new client from the provided config. +func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { + opts := Options{ + Region: cfg.Region, + DefaultsMode: cfg.DefaultsMode, + RuntimeEnvironment: cfg.RuntimeEnvironment, + HTTPClient: cfg.HTTPClient, + Credentials: cfg.Credentials, + APIOptions: cfg.APIOptions, + Logger: cfg.Logger, + ClientLogMode: cfg.ClientLogMode, + AppID: cfg.AppID, + } + resolveAWSRetryerProvider(cfg, &opts) + resolveAWSRetryMaxAttempts(cfg, &opts) + resolveAWSRetryMode(cfg, &opts) + resolveAWSEndpointResolver(cfg, &opts) + resolveUseDualStackEndpoint(cfg, &opts) + resolveUseFIPSEndpoint(cfg, &opts) + resolveBaseEndpoint(cfg, &opts) + return New(opts, optFns...) +} + +func resolveHTTPClient(o *Options) { + var buildable *awshttp.BuildableClient + + if o.HTTPClient != nil { + var ok bool + buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) + if !ok { + return + } + } else { + buildable = awshttp.NewBuildableClient() + } + + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { + if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { + dialer.Timeout = dialerTimeout + } + }) + + buildable = buildable.WithTransportOptions(func(transport *http.Transport) { + if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { + transport.TLSHandshakeTimeout = tlsHandshakeTimeout + } + }) + } + + o.HTTPClient = buildable +} + +func resolveRetryer(o *Options) { + if o.Retryer != nil { + return + } + + if len(o.RetryMode) == 0 { + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + o.RetryMode = modeConfig.RetryMode + } + } + if len(o.RetryMode) == 0 { + o.RetryMode = aws.RetryModeStandard + } + + var standardOptions []func(*retry.StandardOptions) + if v := o.RetryMaxAttempts; v != 0 { + standardOptions = append(standardOptions, func(so *retry.StandardOptions) { + so.MaxAttempts = v + }) + } + + switch o.RetryMode { + case aws.RetryModeAdaptive: + var adaptiveOptions []func(*retry.AdaptiveModeOptions) + if len(standardOptions) != 0 { + adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { + ao.StandardOptions = append(ao.StandardOptions, standardOptions...) + }) + } + o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) + + default: + o.Retryer = retry.NewStandard(standardOptions...) + } +} + +func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { + if cfg.Retryer == nil { + return + } + o.Retryer = cfg.Retryer() +} + +func resolveAWSRetryMode(cfg aws.Config, o *Options) { + if len(cfg.RetryMode) == 0 { + return + } + o.RetryMode = cfg.RetryMode +} +func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { + if cfg.RetryMaxAttempts == 0 { + return + } + o.RetryMaxAttempts = cfg.RetryMaxAttempts +} + +func finalizeRetryMaxAttempts(o *Options) { + if o.RetryMaxAttempts == 0 { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func finalizeOperationRetryMaxAttempts(o *Options, client Client) { + if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { + if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { + return + } + o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) +} + +func addClientUserAgent(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "textract", goModuleVersion) + if len(options.AppID) > 0 { + ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID) + } + + return nil +} + +func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) { + id := (*awsmiddleware.RequestUserAgent)(nil).ID() + mw, ok := stack.Build.Get(id) + if !ok { + mw = awsmiddleware.NewRequestUserAgent() + if err := stack.Build.Add(mw, middleware.After); err != nil { + return nil, err + } + } + + ua, ok := mw.(*awsmiddleware.RequestUserAgent) + if !ok { + return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id) + } + + return ua, nil +} + +type HTTPSignerV4 interface { + SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error +} + +func resolveHTTPSignerV4(o *Options) { + if o.HTTPSignerV4 != nil { + return + } + o.HTTPSignerV4 = newDefaultV4Signer(*o) +} + +func newDefaultV4Signer(o Options) *v4.Signer { + return v4.NewSigner(func(so *v4.SignerOptions) { + so.Logger = o.Logger + so.LogSigning = o.ClientLogMode.IsSigning() + }) +} + +func addClientRequestID(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After) +} + +func addComputeContentLength(stack *middleware.Stack) error { + return stack.Build.Add(&smithyhttp.ComputeContentLength{}, middleware.After) +} + +func addRawResponseToMetadata(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before) +} + +func addRecordResponseTiming(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{}, middleware.After) +} + +func addSpanRetryLoop(stack *middleware.Stack, options Options) error { + return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before) +} + +type spanRetryLoop struct { + options Options +} + +func (*spanRetryLoop) ID() string { + return "spanRetryLoop" +} + +func (m *spanRetryLoop) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, +) ( + middleware.FinalizeOutput, middleware.Metadata, error, +) { + tracer := operationTracer(m.options.TracerProvider) + ctx, span := tracer.StartSpan(ctx, "RetryLoop") + defer span.End() + + return next.HandleFinalize(ctx, in) +} +func addStreamingEventsPayload(stack *middleware.Stack) error { + return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before) +} + +func addUnsignedPayload(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After) +} + +func addComputePayloadSHA256(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After) +} + +func addContentSHA256Header(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After) +} + +func addIsWaiterUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter) + return nil + }) +} + +func addIsPaginatorUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator) + return nil + }) +} + +func resolveIdempotencyTokenProvider(o *Options) { + if o.IdempotencyTokenProvider != nil { + return + } + o.IdempotencyTokenProvider = smithyrand.NewUUIDIdempotencyToken(cryptorand.Reader) +} + +func addRetry(stack *middleware.Stack, o Options) error { + attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) { + m.LogAttempts = o.ClientLogMode.IsRetries() + m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/textract") + }) + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { + return err + } + if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { + return err + } + return nil +} + +// resolves dual-stack endpoint configuration +func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseDualStackEndpoint = value + } + return nil +} + +// resolves FIPS endpoint configuration +func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseFIPSEndpoint = value + } + return nil +} + +func resolveAccountID(identity smithyauth.Identity, mode aws.AccountIDEndpointMode) *string { + if mode == aws.AccountIDEndpointModeDisabled { + return nil + } + + if ca, ok := identity.(*internalauthsmithy.CredentialsAdapter); ok && ca.Credentials.AccountID != "" { + return aws.String(ca.Credentials.AccountID) + } + + return nil +} + +func addTimeOffsetBuild(stack *middleware.Stack, c *Client) error { + mw := internalmiddleware.AddTimeOffsetMiddleware{Offset: c.timeOffset} + if err := stack.Build.Add(&mw, middleware.After); err != nil { + return err + } + return stack.Deserialize.Insert(&mw, "RecordResponseTiming", middleware.Before) +} +func initializeTimeOffsetResolver(c *Client) { + c.timeOffset = new(atomic.Int64) +} + +func addUserAgentRetryMode(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + switch options.Retryer.(type) { + case *retry.Standard: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard) + case *retry.AdaptiveMode: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive) + } + return nil +} + +type setCredentialSourceMiddleware struct { + ua *awsmiddleware.RequestUserAgent + options Options +} + +func (m setCredentialSourceMiddleware) ID() string { return "SetCredentialSourceMiddleware" } + +func (m setCredentialSourceMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( + out middleware.BuildOutput, metadata middleware.Metadata, err error, +) { + asProviderSource, ok := m.options.Credentials.(aws.CredentialProviderSource) + if !ok { + return next.HandleBuild(ctx, in) + } + providerSources := asProviderSource.ProviderSources() + for _, source := range providerSources { + m.ua.AddCredentialsSource(source) + } + return next.HandleBuild(ctx, in) +} + +func addCredentialSource(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + mw := setCredentialSourceMiddleware{ua: ua, options: options} + return stack.Build.Insert(&mw, "UserAgent", middleware.Before) +} + +func resolveTracerProvider(options *Options) { + if options.TracerProvider == nil { + options.TracerProvider = &tracing.NopTracerProvider{} + } +} + +func resolveMeterProvider(options *Options) { + if options.MeterProvider == nil { + options.MeterProvider = metrics.NopMeterProvider{} + } +} + +// IdempotencyTokenProvider interface for providing idempotency token +type IdempotencyTokenProvider interface { + GetIdempotencyToken() (string, error) +} + +func addRecursionDetection(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After) +} + +func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before) + +} + +func addResponseErrorMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before) + +} + +func addRequestResponseLogging(stack *middleware.Stack, o Options) error { + return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ + LogRequest: o.ClientLogMode.IsRequest(), + LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), + LogResponse: o.ClientLogMode.IsResponse(), + LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), + }, middleware.After) +} + +type disableHTTPSMiddleware struct { + DisableHTTPS bool +} + +func (*disableHTTPSMiddleware) ID() string { + return "disableHTTPS" +} + +func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { + req.URL.Scheme = "http" + } + + return next.HandleFinalize(ctx, in) +} + +func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { + return stack.Finalize.Insert(&disableHTTPSMiddleware{ + DisableHTTPS: o.EndpointOptions.DisableHTTPS, + }, "ResolveEndpointV2", middleware.After) +} + +type spanInitializeStart struct { +} + +func (*spanInitializeStart) ID() string { + return "spanInitializeStart" +} + +func (m *spanInitializeStart) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "Initialize") + + return next.HandleInitialize(ctx, in) +} + +type spanInitializeEnd struct { +} + +func (*spanInitializeEnd) ID() string { + return "spanInitializeEnd" +} + +func (m *spanInitializeEnd) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleInitialize(ctx, in) +} + +type spanBuildRequestStart struct { +} + +func (*spanBuildRequestStart) ID() string { + return "spanBuildRequestStart" +} + +func (m *spanBuildRequestStart) HandleSerialize( + ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, +) ( + middleware.SerializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "BuildRequest") + + return next.HandleSerialize(ctx, in) +} + +type spanBuildRequestEnd struct { +} + +func (*spanBuildRequestEnd) ID() string { + return "spanBuildRequestEnd" +} + +func (m *spanBuildRequestEnd) HandleBuild( + ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, +) ( + middleware.BuildOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleBuild(ctx, in) +} + +func addSpanInitializeStart(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) +} + +func addSpanInitializeEnd(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) +} + +func addSpanBuildRequestStart(stack *middleware.Stack) error { + return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) +} + +func addSpanBuildRequestEnd(stack *middleware.Stack) error { + return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeDocument.go new file mode 100644 index 00000000..21889418 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeDocument.go @@ -0,0 +1,237 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Analyzes an input document for relationships between detected items. +// +// The types of information returned are as follows: +// +// - Form data (key-value pairs). The related information is returned in two Block +// objects, each of type KEY_VALUE_SET : a KEY Block object and a VALUE Block +// object. For example, Name: Ana Silva Carolina contains a key and value. Name: is +// the key. Ana Silva Carolina is the value. +// +// - Table and table cell data. A TABLE Block object contains information about a +// detected table. A CELL Block object is returned for each cell in a table. +// +// - Lines and words of text. A LINE Block object contains one or more WORD Block +// objects. All lines and words that are detected in the document are returned +// (including text that doesn't have a relationship with the value of +// FeatureTypes ). +// +// - Signatures. A SIGNATURE Block object contains the location information of a +// signature in a document. If used in conjunction with forms or tables, a +// signature can be given a Key-Value pairing or be detected in the cell of a +// table. +// +// - Query. A QUERY Block object contains the query text, alias and link to the +// associated Query results block object. +// +// - Query Result. A QUERY_RESULT Block object contains the answer to the query +// and an ID that connects it to the query asked. This Block also contains a +// confidence score. +// +// Selection elements such as check boxes and option buttons (radio buttons) can +// be detected in form data and in tables. A SELECTION_ELEMENT Block object +// contains information about a selection element, including the selection status. +// +// You can choose which type of analysis to perform by specifying the FeatureTypes +// list. +// +// The output is returned in a list of Block objects. +// +// AnalyzeDocument is a synchronous operation. To analyze documents +// asynchronously, use StartDocumentAnalysis. +// +// For more information, see [Document Text Analysis]. +// +// [Document Text Analysis]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-analyzing.html +func (c *Client) AnalyzeDocument(ctx context.Context, params *AnalyzeDocumentInput, optFns ...func(*Options)) (*AnalyzeDocumentOutput, error) { + if params == nil { + params = &AnalyzeDocumentInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AnalyzeDocument", params, optFns, c.addOperationAnalyzeDocumentMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AnalyzeDocumentOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AnalyzeDocumentInput struct { + + // The input document as base64-encoded bytes or an Amazon S3 object. If you use + // the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The + // document must be an image in JPEG, PNG, PDF, or TIFF format. + // + // If you're using an AWS SDK to call Amazon Textract, you might not need to + // base64-encode image bytes that are passed using the Bytes field. + // + // This member is required. + Document *types.Document + + // A list of the types of analysis to perform. Add TABLES to the list to return + // information about the tables that are detected in the input document. Add FORMS + // to return detected form data. Add SIGNATURES to return the locations of detected + // signatures. Add LAYOUT to the list to return information about the layout of the + // document. All lines and words detected in the document are included in the + // response (including text that isn't related to the value of FeatureTypes ). + // + // This member is required. + FeatureTypes []types.FeatureType + + // Specifies the adapter to be used when analyzing a document. + AdaptersConfig *types.AdaptersConfig + + // Sets the configuration for the human in the loop workflow for analyzing + // documents. + HumanLoopConfig *types.HumanLoopConfig + + // Contains Queries and the alias for those Queries, as determined by the input. + QueriesConfig *types.QueriesConfig + + noSmithyDocumentSerde +} + +type AnalyzeDocumentOutput struct { + + // The version of the model used to analyze the document. + AnalyzeDocumentModelVersion *string + + // The items that are detected and analyzed by AnalyzeDocument . + Blocks []types.Block + + // Metadata about the analyzed document. An example is the number of pages. + DocumentMetadata *types.DocumentMetadata + + // Shows the results of the human in the loop evaluation. + HumanLoopActivationOutput *types.HumanLoopActivationOutput + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAnalyzeDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAnalyzeDocument{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAnalyzeDocument{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AnalyzeDocument"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAnalyzeDocumentValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAnalyzeDocument(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAnalyzeDocument(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AnalyzeDocument", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeExpense.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeExpense.go new file mode 100644 index 00000000..6db6f7e3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeExpense.go @@ -0,0 +1,192 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// AnalyzeExpense synchronously analyzes an input document for financially related +// relationships between text. +// +// Information is returned as ExpenseDocuments and seperated as follows: +// +// - LineItemGroups - A data set containing LineItems which store information +// about the lines of text, such as an item purchased and its price on a receipt. +// +// - SummaryFields - Contains all other information a receipt, such as header +// information or the vendors name. +func (c *Client) AnalyzeExpense(ctx context.Context, params *AnalyzeExpenseInput, optFns ...func(*Options)) (*AnalyzeExpenseOutput, error) { + if params == nil { + params = &AnalyzeExpenseInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AnalyzeExpense", params, optFns, c.addOperationAnalyzeExpenseMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AnalyzeExpenseOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AnalyzeExpenseInput struct { + + // The input document, either as bytes or as an S3 object. + // + // You pass image bytes to an Amazon Textract API operation by using the Bytes + // property. For example, you would use the Bytes property to pass a document + // loaded from a local file system. Image bytes passed by using the Bytes property + // must be base64 encoded. Your code might not need to encode document file bytes + // if you're using an AWS SDK to call Amazon Textract API operations. + // + // You pass images stored in an S3 bucket to an Amazon Textract API operation by + // using the S3Object property. Documents stored in an S3 bucket don't need to be + // base64 encoded. + // + // The AWS Region for the S3 bucket that contains the S3 object must match the AWS + // Region that you use for Amazon Textract operations. + // + // If you use the AWS CLI to call Amazon Textract operations, passing image bytes + // using the Bytes property isn't supported. You must first upload the document to + // an Amazon S3 bucket, and then call the operation using the S3Object property. + // + // For Amazon Textract to process an S3 object, the user must have permission to + // access the S3 object. + // + // This member is required. + Document *types.Document + + noSmithyDocumentSerde +} + +type AnalyzeExpenseOutput struct { + + // Information about the input document. + DocumentMetadata *types.DocumentMetadata + + // The expenses detected by Amazon Textract. + ExpenseDocuments []types.ExpenseDocument + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAnalyzeExpenseMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAnalyzeExpense{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAnalyzeExpense{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AnalyzeExpense"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAnalyzeExpenseValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAnalyzeExpense(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAnalyzeExpense(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AnalyzeExpense", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeID.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeID.go new file mode 100644 index 00000000..c79776e7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_AnalyzeID.go @@ -0,0 +1,170 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Analyzes identity documents for relevant information. This information is +// extracted and returned as IdentityDocumentFields , which records both the +// normalized field and value of the extracted text. Unlike other Amazon Textract +// operations, AnalyzeID doesn't return any Geometry data. +func (c *Client) AnalyzeID(ctx context.Context, params *AnalyzeIDInput, optFns ...func(*Options)) (*AnalyzeIDOutput, error) { + if params == nil { + params = &AnalyzeIDInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AnalyzeID", params, optFns, c.addOperationAnalyzeIDMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AnalyzeIDOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AnalyzeIDInput struct { + + // The document being passed to AnalyzeID. + // + // This member is required. + DocumentPages []types.Document + + noSmithyDocumentSerde +} + +type AnalyzeIDOutput struct { + + // The version of the AnalyzeIdentity API being used to process documents. + AnalyzeIDModelVersion *string + + // Information about the input document. + DocumentMetadata *types.DocumentMetadata + + // The list of documents processed by AnalyzeID. Includes a number denoting their + // place in the list and the response structure for the document. + IdentityDocuments []types.IdentityDocument + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAnalyzeIDMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAnalyzeID{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAnalyzeID{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AnalyzeID"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAnalyzeIDValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAnalyzeID(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAnalyzeID(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AnalyzeID", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapter.go new file mode 100644 index 00000000..e9b79b71 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapter.go @@ -0,0 +1,221 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates an adapter, which can be fine-tuned for enhanced performance on user +// provided documents. Takes an AdapterName and FeatureType. Currently the only +// supported feature type is QUERIES . You can also provide a Description, Tags, +// and a ClientRequestToken. You can choose whether or not the adapter should be +// AutoUpdated with the AutoUpdate argument. By default, AutoUpdate is set to +// DISABLED. +func (c *Client) CreateAdapter(ctx context.Context, params *CreateAdapterInput, optFns ...func(*Options)) (*CreateAdapterOutput, error) { + if params == nil { + params = &CreateAdapterInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateAdapter", params, optFns, c.addOperationCreateAdapterMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateAdapterOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateAdapterInput struct { + + // The name to be assigned to the adapter being created. + // + // This member is required. + AdapterName *string + + // The type of feature that the adapter is being trained on. Currrenly, supported + // feature types are: QUERIES + // + // This member is required. + FeatureTypes []types.FeatureType + + // Controls whether or not the adapter should automatically update. + AutoUpdate types.AutoUpdate + + // Idempotent token is used to recognize the request. If the same token is used + // with multiple CreateAdapter requests, the same session is returned. This token + // is employed to avoid unintentionally creating the same session multiple times. + ClientRequestToken *string + + // The description to be assigned to the adapter being created. + Description *string + + // A list of tags to be added to the adapter. + Tags map[string]string + + noSmithyDocumentSerde +} + +type CreateAdapterOutput struct { + + // A string containing the unique ID for the adapter that has been created. + AdapterId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateAdapterMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateAdapter{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateAdapter{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateAdapter"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addIdempotencyToken_opCreateAdapterMiddleware(stack, options); err != nil { + return err + } + if err = addOpCreateAdapterValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateAdapter(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +type idempotencyToken_initializeOpCreateAdapter struct { + tokenProvider IdempotencyTokenProvider +} + +func (*idempotencyToken_initializeOpCreateAdapter) ID() string { + return "OperationIdempotencyTokenAutoFill" +} + +func (m *idempotencyToken_initializeOpCreateAdapter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + if m.tokenProvider == nil { + return next.HandleInitialize(ctx, in) + } + + input, ok := in.Parameters.(*CreateAdapterInput) + if !ok { + return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateAdapterInput ") + } + + if input.ClientRequestToken == nil { + t, err := m.tokenProvider.GetIdempotencyToken() + if err != nil { + return out, metadata, err + } + input.ClientRequestToken = &t + } + return next.HandleInitialize(ctx, in) +} +func addIdempotencyToken_opCreateAdapterMiddleware(stack *middleware.Stack, cfg Options) error { + return stack.Initialize.Add(&idempotencyToken_initializeOpCreateAdapter{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) +} + +func newServiceMetadataMiddleware_opCreateAdapter(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateAdapter", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapterVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapterVersion.go new file mode 100644 index 00000000..d67b4017 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_CreateAdapterVersion.go @@ -0,0 +1,249 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new version of an adapter. Operates on a provided AdapterId and a +// specified dataset provided via the DatasetConfig argument. Requires that you +// specify an Amazon S3 bucket with the OutputConfig argument. You can provide an +// optional KMSKeyId, an optional ClientRequestToken, and optional tags. +func (c *Client) CreateAdapterVersion(ctx context.Context, params *CreateAdapterVersionInput, optFns ...func(*Options)) (*CreateAdapterVersionOutput, error) { + if params == nil { + params = &CreateAdapterVersionInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateAdapterVersion", params, optFns, c.addOperationCreateAdapterVersionMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateAdapterVersionOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateAdapterVersionInput struct { + + // A string containing a unique ID for the adapter that will receive a new version. + // + // This member is required. + AdapterId *string + + // Specifies a dataset used to train a new adapter version. Takes a + // ManifestS3Object as the value. + // + // This member is required. + DatasetConfig *types.AdapterVersionDatasetConfig + + // Sets whether or not your output will go to a user created bucket. Used to set + // the name of the bucket, and the prefix on the output file. + // + // OutputConfig is an optional parameter which lets you adjust where your output + // will be placed. By default, Amazon Textract will store the results internally + // and can only be accessed by the Get API operations. With OutputConfig enabled, + // you can set the name of the bucket the output will be sent to the file prefix of + // the results where you can download your results. Additionally, you can set the + // KMSKeyID parameter to a customer master key (CMK) to encrypt your output. + // Without this parameter set Amazon Textract will encrypt server-side using the + // AWS managed CMK for Amazon S3. + // + // Decryption of Customer Content is necessary for processing of the documents by + // Amazon Textract. If your account is opted out under an AI services opt out + // policy then all unencrypted Customer Content is immediately and permanently + // deleted after the Customer Content has been processed by the service. No copy of + // of the output is retained by Amazon Textract. For information about how to opt + // out, see [Managing AI services opt-out policy.] + // + // For more information on data privacy, see the [Data Privacy FAQ]. + // + // [Managing AI services opt-out policy.]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html + // [Data Privacy FAQ]: https://aws.amazon.com/compliance/data-privacy-faq/ + // + // This member is required. + OutputConfig *types.OutputConfig + + // Idempotent token is used to recognize the request. If the same token is used + // with multiple CreateAdapterVersion requests, the same session is returned. This + // token is employed to avoid unintentionally creating the same session multiple + // times. + ClientRequestToken *string + + // The identifier for your AWS Key Management Service key (AWS KMS key). Used to + // encrypt your documents. + KMSKeyId *string + + // A set of tags (key-value pairs) that you want to attach to the adapter version. + Tags map[string]string + + noSmithyDocumentSerde +} + +type CreateAdapterVersionOutput struct { + + // A string containing the unique ID for the adapter that has received a new + // version. + AdapterId *string + + // A string describing the new version of the adapter. + AdapterVersion *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateAdapterVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateAdapterVersion{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateAdapterVersion{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateAdapterVersion"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addIdempotencyToken_opCreateAdapterVersionMiddleware(stack, options); err != nil { + return err + } + if err = addOpCreateAdapterVersionValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateAdapterVersion(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +type idempotencyToken_initializeOpCreateAdapterVersion struct { + tokenProvider IdempotencyTokenProvider +} + +func (*idempotencyToken_initializeOpCreateAdapterVersion) ID() string { + return "OperationIdempotencyTokenAutoFill" +} + +func (m *idempotencyToken_initializeOpCreateAdapterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + if m.tokenProvider == nil { + return next.HandleInitialize(ctx, in) + } + + input, ok := in.Parameters.(*CreateAdapterVersionInput) + if !ok { + return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateAdapterVersionInput ") + } + + if input.ClientRequestToken == nil { + t, err := m.tokenProvider.GetIdempotencyToken() + if err != nil { + return out, metadata, err + } + input.ClientRequestToken = &t + } + return next.HandleInitialize(ctx, in) +} +func addIdempotencyToken_opCreateAdapterVersionMiddleware(stack *middleware.Stack, cfg Options) error { + return stack.Initialize.Add(&idempotencyToken_initializeOpCreateAdapterVersion{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) +} + +func newServiceMetadataMiddleware_opCreateAdapterVersion(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateAdapterVersion", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapter.go new file mode 100644 index 00000000..6a36fdb2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapter.go @@ -0,0 +1,156 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes an Amazon Textract adapter. Takes an AdapterId and deletes the adapter +// specified by the ID. +func (c *Client) DeleteAdapter(ctx context.Context, params *DeleteAdapterInput, optFns ...func(*Options)) (*DeleteAdapterOutput, error) { + if params == nil { + params = &DeleteAdapterInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteAdapter", params, optFns, c.addOperationDeleteAdapterMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteAdapterOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteAdapterInput struct { + + // A string containing a unique ID for the adapter to be deleted. + // + // This member is required. + AdapterId *string + + noSmithyDocumentSerde +} + +type DeleteAdapterOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteAdapterMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteAdapter{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteAdapter{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteAdapter"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteAdapterValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteAdapter(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteAdapter(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteAdapter", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapterVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapterVersion.go new file mode 100644 index 00000000..f97bb5e9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DeleteAdapterVersion.go @@ -0,0 +1,162 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes an Amazon Textract adapter version. Requires that you specify both an +// AdapterId and a AdapterVersion. Deletes the adapter version specified by the +// AdapterId and the AdapterVersion. +func (c *Client) DeleteAdapterVersion(ctx context.Context, params *DeleteAdapterVersionInput, optFns ...func(*Options)) (*DeleteAdapterVersionOutput, error) { + if params == nil { + params = &DeleteAdapterVersionInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteAdapterVersion", params, optFns, c.addOperationDeleteAdapterVersionMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteAdapterVersionOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteAdapterVersionInput struct { + + // A string containing a unique ID for the adapter version that will be deleted. + // + // This member is required. + AdapterId *string + + // Specifies the adapter version to be deleted. + // + // This member is required. + AdapterVersion *string + + noSmithyDocumentSerde +} + +type DeleteAdapterVersionOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteAdapterVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteAdapterVersion{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteAdapterVersion{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteAdapterVersion"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteAdapterVersionValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteAdapterVersion(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteAdapterVersion(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteAdapterVersion", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DetectDocumentText.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DetectDocumentText.go new file mode 100644 index 00000000..63c78c63 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_DetectDocumentText.go @@ -0,0 +1,187 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Detects text in the input document. Amazon Textract can detect lines of text +// and the words that make up a line of text. The input document must be in one of +// the following image formats: JPEG, PNG, PDF, or TIFF. DetectDocumentText +// returns the detected text in an array of Blockobjects. +// +// Each document page has as an associated Block of type PAGE. Each PAGE Block +// object is the parent of LINE Block objects that represent the lines of detected +// text on a page. A LINE Block object is a parent for each word that makes up the +// line. Words are represented by Block objects of type WORD. +// +// DetectDocumentText is a synchronous operation. To analyze documents +// asynchronously, use StartDocumentTextDetection. +// +// For more information, see [Document Text Detection]. +// +// [Document Text Detection]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-detecting.html +func (c *Client) DetectDocumentText(ctx context.Context, params *DetectDocumentTextInput, optFns ...func(*Options)) (*DetectDocumentTextOutput, error) { + if params == nil { + params = &DetectDocumentTextInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DetectDocumentText", params, optFns, c.addOperationDetectDocumentTextMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DetectDocumentTextOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DetectDocumentTextInput struct { + + // The input document as base64-encoded bytes or an Amazon S3 object. If you use + // the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The + // document must be an image in JPEG or PNG format. + // + // If you're using an AWS SDK to call Amazon Textract, you might not need to + // base64-encode image bytes that are passed using the Bytes field. + // + // This member is required. + Document *types.Document + + noSmithyDocumentSerde +} + +type DetectDocumentTextOutput struct { + + // An array of Block objects that contain the text that's detected in the document. + Blocks []types.Block + + // + DetectDocumentTextModelVersion *string + + // Metadata about the document. It contains the number of pages that are detected + // in the document. + DocumentMetadata *types.DocumentMetadata + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDetectDocumentTextMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDetectDocumentText{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDetectDocumentText{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DetectDocumentText"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDetectDocumentTextValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDetectDocumentText(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDetectDocumentText(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DetectDocumentText", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapter.go new file mode 100644 index 00000000..37ddfc14 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapter.go @@ -0,0 +1,182 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Gets configuration information for an adapter specified by an AdapterId, +// returning information on AdapterName, Description, CreationTime, AutoUpdate +// status, and FeatureTypes. +func (c *Client) GetAdapter(ctx context.Context, params *GetAdapterInput, optFns ...func(*Options)) (*GetAdapterOutput, error) { + if params == nil { + params = &GetAdapterInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetAdapter", params, optFns, c.addOperationGetAdapterMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetAdapterOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetAdapterInput struct { + + // A string containing a unique ID for the adapter. + // + // This member is required. + AdapterId *string + + noSmithyDocumentSerde +} + +type GetAdapterOutput struct { + + // A string identifying the adapter that information has been retrieved for. + AdapterId *string + + // The name of the requested adapter. + AdapterName *string + + // Binary value indicating if the adapter is being automatically updated or not. + AutoUpdate types.AutoUpdate + + // The date and time the requested adapter was created at. + CreationTime *time.Time + + // The description for the requested adapter. + Description *string + + // List of the targeted feature types for the requested adapter. + FeatureTypes []types.FeatureType + + // A set of tags (key-value pairs) associated with the adapter that has been + // retrieved. + Tags map[string]string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetAdapterMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAdapter{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetAdapter{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetAdapter"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetAdapterValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAdapter(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetAdapter(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetAdapter", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapterVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapterVersion.go new file mode 100644 index 00000000..9e009a62 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetAdapterVersion.go @@ -0,0 +1,224 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Gets configuration information for the specified adapter version, including: +// AdapterId, AdapterVersion, FeatureTypes, Status, StatusMessage, DatasetConfig, +// KMSKeyId, OutputConfig, Tags and EvaluationMetrics. +func (c *Client) GetAdapterVersion(ctx context.Context, params *GetAdapterVersionInput, optFns ...func(*Options)) (*GetAdapterVersionOutput, error) { + if params == nil { + params = &GetAdapterVersionInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetAdapterVersion", params, optFns, c.addOperationGetAdapterVersionMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetAdapterVersionOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetAdapterVersionInput struct { + + // A string specifying a unique ID for the adapter version you want to retrieve + // information for. + // + // This member is required. + AdapterId *string + + // A string specifying the adapter version you want to retrieve information for. + // + // This member is required. + AdapterVersion *string + + noSmithyDocumentSerde +} + +type GetAdapterVersionOutput struct { + + // A string containing a unique ID for the adapter version being retrieved. + AdapterId *string + + // A string containing the adapter version that has been retrieved. + AdapterVersion *string + + // The time that the adapter version was created. + CreationTime *time.Time + + // Specifies a dataset used to train a new adapter version. Takes a + // ManifestS3Objec as the value. + DatasetConfig *types.AdapterVersionDatasetConfig + + // The evaluation metrics (F1 score, Precision, and Recall) for the requested + // version, grouped by baseline metrics and adapter version. + EvaluationMetrics []types.AdapterVersionEvaluationMetric + + // List of the targeted feature types for the requested adapter version. + FeatureTypes []types.FeatureType + + // The identifier for your AWS Key Management Service key (AWS KMS key). Used to + // encrypt your documents. + KMSKeyId *string + + // Sets whether or not your output will go to a user created bucket. Used to set + // the name of the bucket, and the prefix on the output file. + // + // OutputConfig is an optional parameter which lets you adjust where your output + // will be placed. By default, Amazon Textract will store the results internally + // and can only be accessed by the Get API operations. With OutputConfig enabled, + // you can set the name of the bucket the output will be sent to the file prefix of + // the results where you can download your results. Additionally, you can set the + // KMSKeyID parameter to a customer master key (CMK) to encrypt your output. + // Without this parameter set Amazon Textract will encrypt server-side using the + // AWS managed CMK for Amazon S3. + // + // Decryption of Customer Content is necessary for processing of the documents by + // Amazon Textract. If your account is opted out under an AI services opt out + // policy then all unencrypted Customer Content is immediately and permanently + // deleted after the Customer Content has been processed by the service. No copy of + // of the output is retained by Amazon Textract. For information about how to opt + // out, see [Managing AI services opt-out policy.] + // + // For more information on data privacy, see the [Data Privacy FAQ]. + // + // [Managing AI services opt-out policy.]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html + // [Data Privacy FAQ]: https://aws.amazon.com/compliance/data-privacy-faq/ + OutputConfig *types.OutputConfig + + // The status of the adapter version that has been requested. + Status types.AdapterVersionStatus + + // A message that describes the status of the requested adapter version. + StatusMessage *string + + // A set of tags (key-value pairs) that are associated with the adapter version. + Tags map[string]string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetAdapterVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAdapterVersion{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetAdapterVersion{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetAdapterVersion"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetAdapterVersionValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAdapterVersion(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetAdapterVersion(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetAdapterVersion", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentAnalysis.go new file mode 100644 index 00000000..aa2d7008 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentAnalysis.go @@ -0,0 +1,247 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets the results for an Amazon Textract asynchronous operation that analyzes +// text in a document. +// +// You start asynchronous text analysis by calling StartDocumentAnalysis, which returns a job +// identifier ( JobId ). When the text analysis operation finishes, Amazon Textract +// publishes a completion status to the Amazon Simple Notification Service (Amazon +// SNS) topic that's registered in the initial call to StartDocumentAnalysis . To +// get the results of the text-detection operation, first check that the status +// value published to the Amazon SNS topic is SUCCEEDED . If so, call +// GetDocumentAnalysis , and pass the job identifier ( JobId ) from the initial +// call to StartDocumentAnalysis . +// +// GetDocumentAnalysis returns an array of Block objects. The following types of +// information are returned: +// +// - Form data (key-value pairs). The related information is returned in two Block +// objects, each of type KEY_VALUE_SET : a KEY Block object and a VALUE Block +// object. For example, Name: Ana Silva Carolina contains a key and value. Name: is +// the key. Ana Silva Carolina is the value. +// +// - Table and table cell data. A TABLE Block object contains information about a +// detected table. A CELL Block object is returned for each cell in a table. +// +// - Lines and words of text. A LINE Block object contains one or more WORD Block +// objects. All lines and words that are detected in the document are returned +// (including text that doesn't have a relationship with the value of the +// StartDocumentAnalysis FeatureTypes input parameter). +// +// - Query. A QUERY Block object contains the query text, alias and link to the +// associated Query results block object. +// +// - Query Results. A QUERY_RESULT Block object contains the answer to the query +// and an ID that connects it to the query asked. This Block also contains a +// confidence score. +// +// While processing a document with queries, look out for +// INVALID_REQUEST_PARAMETERS output. This indicates that either the per page query +// limit has been exceeded or that the operation is trying to query a page in the +// document which doesn’t exist. +// +// Selection elements such as check boxes and option buttons (radio buttons) can +// be detected in form data and in tables. A SELECTION_ELEMENT Block object +// contains information about a selection element, including the selection status. +// +// Use the MaxResults parameter to limit the number of blocks that are returned. +// If there are more results than specified in MaxResults , the value of NextToken +// in the operation response contains a pagination token for getting the next set +// of results. To get the next page of results, call GetDocumentAnalysis , and +// populate the NextToken request parameter with the token value that's returned +// from the previous call to GetDocumentAnalysis . +// +// For more information, see [Document Text Analysis]. +// +// [Document Text Analysis]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-analyzing.html +func (c *Client) GetDocumentAnalysis(ctx context.Context, params *GetDocumentAnalysisInput, optFns ...func(*Options)) (*GetDocumentAnalysisOutput, error) { + if params == nil { + params = &GetDocumentAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetDocumentAnalysis", params, optFns, c.addOperationGetDocumentAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetDocumentAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetDocumentAnalysisInput struct { + + // A unique identifier for the text-detection job. The JobId is returned from + // StartDocumentAnalysis . A JobId value is only valid for 7 days. + // + // This member is required. + JobId *string + + // The maximum number of results to return per paginated call. The largest value + // that you can specify is 1,000. If you specify a value greater than 1,000, a + // maximum of 1,000 results is returned. The default value is 1,000. + MaxResults *int32 + + // If the previous response was incomplete (because there are more blocks to + // retrieve), Amazon Textract returns a pagination token in the response. You can + // use this pagination token to retrieve the next set of blocks. + NextToken *string + + noSmithyDocumentSerde +} + +type GetDocumentAnalysisOutput struct { + + // + AnalyzeDocumentModelVersion *string + + // The results of the text-analysis operation. + Blocks []types.Block + + // Information about a document that Amazon Textract processed. DocumentMetadata + // is returned in every page of paginated responses from an Amazon Textract video + // operation. + DocumentMetadata *types.DocumentMetadata + + // The current status of the text detection job. + JobStatus types.JobStatus + + // If the response is truncated, Amazon Textract returns this token. You can use + // this token in the subsequent request to retrieve the next set of text detection + // results. + NextToken *string + + // Returns if the detection job could not be completed. Contains explanation for + // what error occured. + StatusMessage *string + + // A list of warnings that occurred during the document-analysis operation. + Warnings []types.Warning + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetDocumentAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDocumentAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDocumentAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetDocumentAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetDocumentAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDocumentAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetDocumentAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetDocumentAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentTextDetection.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentTextDetection.go new file mode 100644 index 00000000..7a5d3922 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetDocumentTextDetection.go @@ -0,0 +1,224 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets the results for an Amazon Textract asynchronous operation that detects +// text in a document. Amazon Textract can detect lines of text and the words that +// make up a line of text. +// +// You start asynchronous text detection by calling StartDocumentTextDetection, which returns a job +// identifier ( JobId ). When the text detection operation finishes, Amazon +// Textract publishes a completion status to the Amazon Simple Notification Service +// (Amazon SNS) topic that's registered in the initial call to +// StartDocumentTextDetection . To get the results of the text-detection operation, +// first check that the status value published to the Amazon SNS topic is SUCCEEDED +// . If so, call GetDocumentTextDetection , and pass the job identifier ( JobId ) +// from the initial call to StartDocumentTextDetection . +// +// GetDocumentTextDetection returns an array of Block objects. +// +// Each document page has as an associated Block of type PAGE. Each PAGE Block +// object is the parent of LINE Block objects that represent the lines of detected +// text on a page. A LINE Block object is a parent for each word that makes up the +// line. Words are represented by Block objects of type WORD. +// +// Use the MaxResults parameter to limit the number of blocks that are returned. +// If there are more results than specified in MaxResults , the value of NextToken +// in the operation response contains a pagination token for getting the next set +// of results. To get the next page of results, call GetDocumentTextDetection , and +// populate the NextToken request parameter with the token value that's returned +// from the previous call to GetDocumentTextDetection . +// +// For more information, see [Document Text Detection]. +// +// [Document Text Detection]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-detecting.html +func (c *Client) GetDocumentTextDetection(ctx context.Context, params *GetDocumentTextDetectionInput, optFns ...func(*Options)) (*GetDocumentTextDetectionOutput, error) { + if params == nil { + params = &GetDocumentTextDetectionInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetDocumentTextDetection", params, optFns, c.addOperationGetDocumentTextDetectionMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetDocumentTextDetectionOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetDocumentTextDetectionInput struct { + + // A unique identifier for the text detection job. The JobId is returned from + // StartDocumentTextDetection . A JobId value is only valid for 7 days. + // + // This member is required. + JobId *string + + // The maximum number of results to return per paginated call. The largest value + // you can specify is 1,000. If you specify a value greater than 1,000, a maximum + // of 1,000 results is returned. The default value is 1,000. + MaxResults *int32 + + // If the previous response was incomplete (because there are more blocks to + // retrieve), Amazon Textract returns a pagination token in the response. You can + // use this pagination token to retrieve the next set of blocks. + NextToken *string + + noSmithyDocumentSerde +} + +type GetDocumentTextDetectionOutput struct { + + // The results of the text-detection operation. + Blocks []types.Block + + // + DetectDocumentTextModelVersion *string + + // Information about a document that Amazon Textract processed. DocumentMetadata + // is returned in every page of paginated responses from an Amazon Textract video + // operation. + DocumentMetadata *types.DocumentMetadata + + // The current status of the text detection job. + JobStatus types.JobStatus + + // If the response is truncated, Amazon Textract returns this token. You can use + // this token in the subsequent request to retrieve the next set of text-detection + // results. + NextToken *string + + // Returns if the detection job could not be completed. Contains explanation for + // what error occured. + StatusMessage *string + + // A list of warnings that occurred during the text-detection operation for the + // document. + Warnings []types.Warning + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetDocumentTextDetectionMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDocumentTextDetection{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDocumentTextDetection{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetDocumentTextDetection"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetDocumentTextDetectionValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDocumentTextDetection(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetDocumentTextDetection(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetDocumentTextDetection", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetExpenseAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetExpenseAnalysis.go new file mode 100644 index 00000000..6d74eb52 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetExpenseAnalysis.go @@ -0,0 +1,217 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets the results for an Amazon Textract asynchronous operation that analyzes +// invoices and receipts. Amazon Textract finds contact information, items +// purchased, and vendor name, from input invoices and receipts. +// +// You start asynchronous invoice/receipt analysis by calling StartExpenseAnalysis, which returns a +// job identifier ( JobId ). Upon completion of the invoice/receipt analysis, +// Amazon Textract publishes the completion status to the Amazon Simple +// Notification Service (Amazon SNS) topic. This topic must be registered in the +// initial call to StartExpenseAnalysis . To get the results of the invoice/receipt +// analysis operation, first ensure that the status value published to the Amazon +// SNS topic is SUCCEEDED . If so, call GetExpenseAnalysis , and pass the job +// identifier ( JobId ) from the initial call to StartExpenseAnalysis . +// +// Use the MaxResults parameter to limit the number of blocks that are returned. +// If there are more results than specified in MaxResults , the value of NextToken +// in the operation response contains a pagination token for getting the next set +// of results. To get the next page of results, call GetExpenseAnalysis , and +// populate the NextToken request parameter with the token value that's returned +// from the previous call to GetExpenseAnalysis . +// +// For more information, see [Analyzing Invoices and Receipts]. +// +// [Analyzing Invoices and Receipts]: https://docs.aws.amazon.com/textract/latest/dg/invoices-receipts.html +func (c *Client) GetExpenseAnalysis(ctx context.Context, params *GetExpenseAnalysisInput, optFns ...func(*Options)) (*GetExpenseAnalysisOutput, error) { + if params == nil { + params = &GetExpenseAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetExpenseAnalysis", params, optFns, c.addOperationGetExpenseAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetExpenseAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetExpenseAnalysisInput struct { + + // A unique identifier for the text detection job. The JobId is returned from + // StartExpenseAnalysis . A JobId value is only valid for 7 days. + // + // This member is required. + JobId *string + + // The maximum number of results to return per paginated call. The largest value + // you can specify is 20. If you specify a value greater than 20, a maximum of 20 + // results is returned. The default value is 20. + MaxResults *int32 + + // If the previous response was incomplete (because there are more blocks to + // retrieve), Amazon Textract returns a pagination token in the response. You can + // use this pagination token to retrieve the next set of blocks. + NextToken *string + + noSmithyDocumentSerde +} + +type GetExpenseAnalysisOutput struct { + + // The current model version of AnalyzeExpense. + AnalyzeExpenseModelVersion *string + + // Information about a document that Amazon Textract processed. DocumentMetadata + // is returned in every page of paginated responses from an Amazon Textract + // operation. + DocumentMetadata *types.DocumentMetadata + + // The expenses detected by Amazon Textract. + ExpenseDocuments []types.ExpenseDocument + + // The current status of the text detection job. + JobStatus types.JobStatus + + // If the response is truncated, Amazon Textract returns this token. You can use + // this token in the subsequent request to retrieve the next set of text-detection + // results. + NextToken *string + + // Returns if the detection job could not be completed. Contains explanation for + // what error occured. + StatusMessage *string + + // A list of warnings that occurred during the text-detection operation for the + // document. + Warnings []types.Warning + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetExpenseAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetExpenseAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetExpenseAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetExpenseAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetExpenseAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetExpenseAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetExpenseAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetExpenseAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysis.go new file mode 100644 index 00000000..72449187 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysis.go @@ -0,0 +1,205 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets the results for an Amazon Textract asynchronous operation that analyzes +// text in a lending document. +// +// You start asynchronous text analysis by calling StartLendingAnalysis , which +// returns a job identifier ( JobId ). When the text analysis operation finishes, +// Amazon Textract publishes a completion status to the Amazon Simple Notification +// Service (Amazon SNS) topic that's registered in the initial call to +// StartLendingAnalysis . +// +// To get the results of the text analysis operation, first check that the status +// value published to the Amazon SNS topic is SUCCEEDED. If so, call +// GetLendingAnalysis, and pass the job identifier ( JobId ) from the initial call +// to StartLendingAnalysis . +func (c *Client) GetLendingAnalysis(ctx context.Context, params *GetLendingAnalysisInput, optFns ...func(*Options)) (*GetLendingAnalysisOutput, error) { + if params == nil { + params = &GetLendingAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetLendingAnalysis", params, optFns, c.addOperationGetLendingAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetLendingAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetLendingAnalysisInput struct { + + // A unique identifier for the lending or text-detection job. The JobId is + // returned from StartLendingAnalysis . A JobId value is only valid for 7 days. + // + // This member is required. + JobId *string + + // The maximum number of results to return per paginated call. The largest value + // that you can specify is 30. If you specify a value greater than 30, a maximum of + // 30 results is returned. The default value is 30. + MaxResults *int32 + + // If the previous response was incomplete, Amazon Textract returns a pagination + // token in the response. You can use this pagination token to retrieve the next + // set of lending results. + NextToken *string + + noSmithyDocumentSerde +} + +type GetLendingAnalysisOutput struct { + + // The current model version of the Analyze Lending API. + AnalyzeLendingModelVersion *string + + // Information about the input document. + DocumentMetadata *types.DocumentMetadata + + // The current status of the lending analysis job. + JobStatus types.JobStatus + + // If the response is truncated, Amazon Textract returns this token. You can use + // this token in the subsequent request to retrieve the next set of lending + // results. + NextToken *string + + // Holds the information returned by one of AmazonTextract's document analysis + // operations for the pinstripe. + Results []types.LendingResult + + // Returns if the lending analysis job could not be completed. Contains + // explanation for what error occurred. + StatusMessage *string + + // A list of warnings that occurred during the lending analysis operation. + Warnings []types.Warning + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetLendingAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetLendingAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetLendingAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetLendingAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetLendingAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetLendingAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetLendingAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetLendingAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysisSummary.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysisSummary.go new file mode 100644 index 00000000..669f9e98 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_GetLendingAnalysisSummary.go @@ -0,0 +1,192 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets summarized results for the StartLendingAnalysis operation, which analyzes +// text in a lending document. The returned summary consists of information about +// documents grouped together by a common document type. Information like detected +// signatures, page numbers, and split documents is returned with respect to the +// type of grouped document. +// +// You start asynchronous text analysis by calling StartLendingAnalysis , which +// returns a job identifier ( JobId ). When the text analysis operation finishes, +// Amazon Textract publishes a completion status to the Amazon Simple Notification +// Service (Amazon SNS) topic that's registered in the initial call to +// StartLendingAnalysis . +// +// To get the results of the text analysis operation, first check that the status +// value published to the Amazon SNS topic is SUCCEEDED. If so, call +// GetLendingAnalysisSummary , and pass the job identifier ( JobId ) from the +// initial call to StartLendingAnalysis . +func (c *Client) GetLendingAnalysisSummary(ctx context.Context, params *GetLendingAnalysisSummaryInput, optFns ...func(*Options)) (*GetLendingAnalysisSummaryOutput, error) { + if params == nil { + params = &GetLendingAnalysisSummaryInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetLendingAnalysisSummary", params, optFns, c.addOperationGetLendingAnalysisSummaryMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetLendingAnalysisSummaryOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetLendingAnalysisSummaryInput struct { + + // A unique identifier for the lending or text-detection job. The JobId is + // returned from StartLendingAnalysis. A JobId value is only valid for 7 days. + // + // This member is required. + JobId *string + + noSmithyDocumentSerde +} + +type GetLendingAnalysisSummaryOutput struct { + + // The current model version of the Analyze Lending API. + AnalyzeLendingModelVersion *string + + // Information about the input document. + DocumentMetadata *types.DocumentMetadata + + // The current status of the lending analysis job. + JobStatus types.JobStatus + + // Returns if the lending analysis could not be completed. Contains explanation + // for what error occurred. + StatusMessage *string + + // Contains summary information for documents grouped by type. + Summary *types.LendingSummary + + // A list of warnings that occurred during the lending analysis operation. + Warnings []types.Warning + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetLendingAnalysisSummaryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetLendingAnalysisSummary{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetLendingAnalysisSummary{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetLendingAnalysisSummary"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetLendingAnalysisSummaryValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetLendingAnalysisSummary(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetLendingAnalysisSummary(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetLendingAnalysisSummary", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapterVersions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapterVersions.go new file mode 100644 index 00000000..47da0c84 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapterVersions.go @@ -0,0 +1,271 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// List all version of an adapter that meet the specified filtration criteria. +func (c *Client) ListAdapterVersions(ctx context.Context, params *ListAdapterVersionsInput, optFns ...func(*Options)) (*ListAdapterVersionsOutput, error) { + if params == nil { + params = &ListAdapterVersionsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListAdapterVersions", params, optFns, c.addOperationListAdapterVersionsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListAdapterVersionsOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListAdapterVersionsInput struct { + + // A string containing a unique ID for the adapter to match for when listing + // adapter versions. + AdapterId *string + + // Specifies the lower bound for the ListAdapterVersions operation. Ensures + // ListAdapterVersions returns only adapter versions created after the specified + // creation time. + AfterCreationTime *time.Time + + // Specifies the upper bound for the ListAdapterVersions operation. Ensures + // ListAdapterVersions returns only adapter versions created after the specified + // creation time. + BeforeCreationTime *time.Time + + // The maximum number of results to return when listing adapter versions. + MaxResults *int32 + + // Identifies the next page of results to return when listing adapter versions. + NextToken *string + + noSmithyDocumentSerde +} + +type ListAdapterVersionsOutput struct { + + // Adapter versions that match the filtering criteria specified when calling + // ListAdapters. + AdapterVersions []types.AdapterVersionOverview + + // Identifies the next page of results to return when listing adapter versions. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListAdapterVersionsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListAdapterVersions{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListAdapterVersions{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListAdapterVersions"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAdapterVersions(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListAdapterVersionsPaginatorOptions is the paginator options for +// ListAdapterVersions +type ListAdapterVersionsPaginatorOptions struct { + // The maximum number of results to return when listing adapter versions. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListAdapterVersionsPaginator is a paginator for ListAdapterVersions +type ListAdapterVersionsPaginator struct { + options ListAdapterVersionsPaginatorOptions + client ListAdapterVersionsAPIClient + params *ListAdapterVersionsInput + nextToken *string + firstPage bool +} + +// NewListAdapterVersionsPaginator returns a new ListAdapterVersionsPaginator +func NewListAdapterVersionsPaginator(client ListAdapterVersionsAPIClient, params *ListAdapterVersionsInput, optFns ...func(*ListAdapterVersionsPaginatorOptions)) *ListAdapterVersionsPaginator { + if params == nil { + params = &ListAdapterVersionsInput{} + } + + options := ListAdapterVersionsPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListAdapterVersionsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListAdapterVersionsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListAdapterVersions page. +func (p *ListAdapterVersionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAdapterVersionsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListAdapterVersions(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListAdapterVersionsAPIClient is a client that implements the +// ListAdapterVersions operation. +type ListAdapterVersionsAPIClient interface { + ListAdapterVersions(context.Context, *ListAdapterVersionsInput, ...func(*Options)) (*ListAdapterVersionsOutput, error) +} + +var _ ListAdapterVersionsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListAdapterVersions(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListAdapterVersions", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapters.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapters.go new file mode 100644 index 00000000..10371554 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListAdapters.go @@ -0,0 +1,263 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Lists all adapters that match the specified filtration criteria. +func (c *Client) ListAdapters(ctx context.Context, params *ListAdaptersInput, optFns ...func(*Options)) (*ListAdaptersOutput, error) { + if params == nil { + params = &ListAdaptersInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListAdapters", params, optFns, c.addOperationListAdaptersMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListAdaptersOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListAdaptersInput struct { + + // Specifies the lower bound for the ListAdapters operation. Ensures ListAdapters + // returns only adapters created after the specified creation time. + AfterCreationTime *time.Time + + // Specifies the upper bound for the ListAdapters operation. Ensures ListAdapters + // returns only adapters created before the specified creation time. + BeforeCreationTime *time.Time + + // The maximum number of results to return when listing adapters. + MaxResults *int32 + + // Identifies the next page of results to return when listing adapters. + NextToken *string + + noSmithyDocumentSerde +} + +type ListAdaptersOutput struct { + + // A list of adapters that matches the filtering criteria specified when calling + // ListAdapters. + Adapters []types.AdapterOverview + + // Identifies the next page of results to return when listing adapters. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListAdaptersMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListAdapters{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListAdapters{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListAdapters"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAdapters(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListAdaptersPaginatorOptions is the paginator options for ListAdapters +type ListAdaptersPaginatorOptions struct { + // The maximum number of results to return when listing adapters. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListAdaptersPaginator is a paginator for ListAdapters +type ListAdaptersPaginator struct { + options ListAdaptersPaginatorOptions + client ListAdaptersAPIClient + params *ListAdaptersInput + nextToken *string + firstPage bool +} + +// NewListAdaptersPaginator returns a new ListAdaptersPaginator +func NewListAdaptersPaginator(client ListAdaptersAPIClient, params *ListAdaptersInput, optFns ...func(*ListAdaptersPaginatorOptions)) *ListAdaptersPaginator { + if params == nil { + params = &ListAdaptersInput{} + } + + options := ListAdaptersPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListAdaptersPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListAdaptersPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListAdapters page. +func (p *ListAdaptersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAdaptersOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListAdapters(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListAdaptersAPIClient is a client that implements the ListAdapters operation. +type ListAdaptersAPIClient interface { + ListAdapters(context.Context, *ListAdaptersInput, ...func(*Options)) (*ListAdaptersOutput, error) +} + +var _ ListAdaptersAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListAdapters(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListAdapters", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListTagsForResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListTagsForResource.go new file mode 100644 index 00000000..db76f397 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_ListTagsForResource.go @@ -0,0 +1,159 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists all tags for an Amazon Textract resource. +func (c *Client) ListTagsForResource(ctx context.Context, params *ListTagsForResourceInput, optFns ...func(*Options)) (*ListTagsForResourceOutput, error) { + if params == nil { + params = &ListTagsForResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListTagsForResource", params, optFns, c.addOperationListTagsForResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListTagsForResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListTagsForResourceInput struct { + + // The Amazon Resource Name (ARN) that specifies the resource to list tags for. + // + // This member is required. + ResourceARN *string + + noSmithyDocumentSerde +} + +type ListTagsForResourceOutput struct { + + // A set of tags (key-value pairs) that are part of the requested resource. + Tags map[string]string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListTagsForResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListTagsForResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListTagsForResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListTagsForResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListTagsForResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opListTagsForResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListTagsForResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentAnalysis.go new file mode 100644 index 00000000..11363ac3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentAnalysis.go @@ -0,0 +1,224 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Starts the asynchronous analysis of an input document for relationships between +// detected items such as key-value pairs, tables, and selection elements. +// +// StartDocumentAnalysis can analyze text in documents that are in JPEG, PNG, +// TIFF, and PDF format. The documents are stored in an Amazon S3 bucket. Use DocumentLocationto +// specify the bucket name and file name of the document. +// +// StartDocumentAnalysis returns a job identifier ( JobId ) that you use to get the +// results of the operation. When text analysis is finished, Amazon Textract +// publishes a completion status to the Amazon Simple Notification Service (Amazon +// SNS) topic that you specify in NotificationChannel . To get the results of the +// text analysis operation, first check that the status value published to the +// Amazon SNS topic is SUCCEEDED . If so, call GetDocumentAnalysis, and pass the job identifier ( JobId +// ) from the initial call to StartDocumentAnalysis . +// +// For more information, see [Document Text Analysis]. +// +// [Document Text Analysis]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-analyzing.html +func (c *Client) StartDocumentAnalysis(ctx context.Context, params *StartDocumentAnalysisInput, optFns ...func(*Options)) (*StartDocumentAnalysisOutput, error) { + if params == nil { + params = &StartDocumentAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartDocumentAnalysis", params, optFns, c.addOperationStartDocumentAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartDocumentAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type StartDocumentAnalysisInput struct { + + // The location of the document to be processed. + // + // This member is required. + DocumentLocation *types.DocumentLocation + + // A list of the types of analysis to perform. Add TABLES to the list to return + // information about the tables that are detected in the input document. Add FORMS + // to return detected form data. To perform both types of analysis, add TABLES and + // FORMS to FeatureTypes . All lines and words detected in the document are + // included in the response (including text that isn't related to the value of + // FeatureTypes ). + // + // This member is required. + FeatureTypes []types.FeatureType + + // Specifies the adapter to be used when analyzing a document. + AdaptersConfig *types.AdaptersConfig + + // The idempotent token that you use to identify the start request. If you use the + // same token with multiple StartDocumentAnalysis requests, the same JobId is + // returned. Use ClientRequestToken to prevent the same job from being + // accidentally started more than once. For more information, see [Calling Amazon Textract Asynchronous Operations]. + // + // [Calling Amazon Textract Asynchronous Operations]: https://docs.aws.amazon.com/textract/latest/dg/api-async.html + ClientRequestToken *string + + // An identifier that you specify that's included in the completion notification + // published to the Amazon SNS topic. For example, you can use JobTag to identify + // the type of document that the completion notification corresponds to (such as a + // tax form or a receipt). + JobTag *string + + // The KMS key used to encrypt the inference results. This can be in either Key ID + // or Key Alias format. When a KMS key is provided, the KMS key will be used for + // server-side encryption of the objects in the customer bucket. When this + // parameter is not enabled, the result will be encrypted server side,using SSE-S3. + KMSKeyId *string + + // The Amazon SNS topic ARN that you want Amazon Textract to publish the + // completion status of the operation to. + NotificationChannel *types.NotificationChannel + + // Sets if the output will go to a customer defined bucket. By default, Amazon + // Textract will save the results internally to be accessed by the + // GetDocumentAnalysis operation. + OutputConfig *types.OutputConfig + + // + QueriesConfig *types.QueriesConfig + + noSmithyDocumentSerde +} + +type StartDocumentAnalysisOutput struct { + + // The identifier for the document text detection job. Use JobId to identify the + // job in a subsequent call to GetDocumentAnalysis . A JobId value is only valid + // for 7 days. + JobId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartDocumentAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartDocumentAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartDocumentAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartDocumentAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartDocumentAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartDocumentAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartDocumentAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartDocumentAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentTextDetection.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentTextDetection.go new file mode 100644 index 00000000..bf1d4b27 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartDocumentTextDetection.go @@ -0,0 +1,208 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Starts the asynchronous detection of text in a document. Amazon Textract can +// detect lines of text and the words that make up a line of text. +// +// StartDocumentTextDetection can analyze text in documents that are in JPEG, PNG, +// TIFF, and PDF format. The documents are stored in an Amazon S3 bucket. Use DocumentLocationto +// specify the bucket name and file name of the document. +// +// StartTextDetection returns a job identifier ( JobId ) that you use to get the +// results of the operation. When text detection is finished, Amazon Textract +// publishes a completion status to the Amazon Simple Notification Service (Amazon +// SNS) topic that you specify in NotificationChannel . To get the results of the +// text detection operation, first check that the status value published to the +// Amazon SNS topic is SUCCEEDED . If so, call GetDocumentTextDetection, and pass the job identifier ( JobId +// ) from the initial call to StartDocumentTextDetection . +// +// For more information, see [Document Text Detection]. +// +// [Document Text Detection]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works-detecting.html +func (c *Client) StartDocumentTextDetection(ctx context.Context, params *StartDocumentTextDetectionInput, optFns ...func(*Options)) (*StartDocumentTextDetectionOutput, error) { + if params == nil { + params = &StartDocumentTextDetectionInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartDocumentTextDetection", params, optFns, c.addOperationStartDocumentTextDetectionMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartDocumentTextDetectionOutput) + out.ResultMetadata = metadata + return out, nil +} + +type StartDocumentTextDetectionInput struct { + + // The location of the document to be processed. + // + // This member is required. + DocumentLocation *types.DocumentLocation + + // The idempotent token that's used to identify the start request. If you use the + // same token with multiple StartDocumentTextDetection requests, the same JobId is + // returned. Use ClientRequestToken to prevent the same job from being + // accidentally started more than once. For more information, see [Calling Amazon Textract Asynchronous Operations]. + // + // [Calling Amazon Textract Asynchronous Operations]: https://docs.aws.amazon.com/textract/latest/dg/api-async.html + ClientRequestToken *string + + // An identifier that you specify that's included in the completion notification + // published to the Amazon SNS topic. For example, you can use JobTag to identify + // the type of document that the completion notification corresponds to (such as a + // tax form or a receipt). + JobTag *string + + // The KMS key used to encrypt the inference results. This can be in either Key ID + // or Key Alias format. When a KMS key is provided, the KMS key will be used for + // server-side encryption of the objects in the customer bucket. When this + // parameter is not enabled, the result will be encrypted server side,using SSE-S3. + KMSKeyId *string + + // The Amazon SNS topic ARN that you want Amazon Textract to publish the + // completion status of the operation to. + NotificationChannel *types.NotificationChannel + + // Sets if the output will go to a customer defined bucket. By default Amazon + // Textract will save the results internally to be accessed with the + // GetDocumentTextDetection operation. + OutputConfig *types.OutputConfig + + noSmithyDocumentSerde +} + +type StartDocumentTextDetectionOutput struct { + + // The identifier of the text detection job for the document. Use JobId to + // identify the job in a subsequent call to GetDocumentTextDetection . A JobId + // value is only valid for 7 days. + JobId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartDocumentTextDetectionMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartDocumentTextDetection{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartDocumentTextDetection{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartDocumentTextDetection"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartDocumentTextDetectionValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartDocumentTextDetection(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartDocumentTextDetection(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartDocumentTextDetection", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartExpenseAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartExpenseAnalysis.go new file mode 100644 index 00000000..d4b6a78a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartExpenseAnalysis.go @@ -0,0 +1,209 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Starts the asynchronous analysis of invoices or receipts for data like contact +// information, items purchased, and vendor names. +// +// StartExpenseAnalysis can analyze text in documents that are in JPEG, PNG, and +// PDF format. The documents must be stored in an Amazon S3 bucket. Use the DocumentLocation +// parameter to specify the name of your S3 bucket and the name of the document in +// that bucket. +// +// StartExpenseAnalysis returns a job identifier ( JobId ) that you will provide to +// GetExpenseAnalysis to retrieve the results of the operation. When the analysis +// of the input invoices/receipts is finished, Amazon Textract publishes a +// completion status to the Amazon Simple Notification Service (Amazon SNS) topic +// that you provide to the NotificationChannel . To obtain the results of the +// invoice and receipt analysis operation, ensure that the status value published +// to the Amazon SNS topic is SUCCEEDED . If so, call GetExpenseAnalysis, and pass the job +// identifier ( JobId ) that was returned by your call to StartExpenseAnalysis . +// +// For more information, see [Analyzing Invoices and Receipts]. +// +// [Analyzing Invoices and Receipts]: https://docs.aws.amazon.com/textract/latest/dg/invoice-receipts.html +func (c *Client) StartExpenseAnalysis(ctx context.Context, params *StartExpenseAnalysisInput, optFns ...func(*Options)) (*StartExpenseAnalysisOutput, error) { + if params == nil { + params = &StartExpenseAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartExpenseAnalysis", params, optFns, c.addOperationStartExpenseAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartExpenseAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type StartExpenseAnalysisInput struct { + + // The location of the document to be processed. + // + // This member is required. + DocumentLocation *types.DocumentLocation + + // The idempotent token that's used to identify the start request. If you use the + // same token with multiple StartDocumentTextDetection requests, the same JobId is + // returned. Use ClientRequestToken to prevent the same job from being + // accidentally started more than once. For more information, see [Calling Amazon Textract Asynchronous Operations] + // + // [Calling Amazon Textract Asynchronous Operations]: https://docs.aws.amazon.com/textract/latest/dg/api-async.html + ClientRequestToken *string + + // An identifier you specify that's included in the completion notification + // published to the Amazon SNS topic. For example, you can use JobTag to identify + // the type of document that the completion notification corresponds to (such as a + // tax form or a receipt). + JobTag *string + + // The KMS key used to encrypt the inference results. This can be in either Key ID + // or Key Alias format. When a KMS key is provided, the KMS key will be used for + // server-side encryption of the objects in the customer bucket. When this + // parameter is not enabled, the result will be encrypted server side,using SSE-S3. + KMSKeyId *string + + // The Amazon SNS topic ARN that you want Amazon Textract to publish the + // completion status of the operation to. + NotificationChannel *types.NotificationChannel + + // Sets if the output will go to a customer defined bucket. By default, Amazon + // Textract will save the results internally to be accessed by the + // GetExpenseAnalysis operation. + OutputConfig *types.OutputConfig + + noSmithyDocumentSerde +} + +type StartExpenseAnalysisOutput struct { + + // A unique identifier for the text detection job. The JobId is returned from + // StartExpenseAnalysis . A JobId value is only valid for 7 days. + JobId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartExpenseAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartExpenseAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartExpenseAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartExpenseAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartExpenseAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartExpenseAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartExpenseAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartExpenseAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartLendingAnalysis.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartLendingAnalysis.go new file mode 100644 index 00000000..633da403 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_StartLendingAnalysis.go @@ -0,0 +1,241 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Starts the classification and analysis of an input document. +// StartLendingAnalysis initiates the classification and analysis of a packet of +// lending documents. StartLendingAnalysis operates on a document file located in +// an Amazon S3 bucket. +// +// StartLendingAnalysis can analyze text in documents that are in one of the +// following formats: JPEG, PNG, TIFF, PDF. Use DocumentLocation to specify the +// bucket name and the file name of the document. +// +// StartLendingAnalysis returns a job identifier ( JobId ) that you use to get the +// results of the operation. When the text analysis is finished, Amazon Textract +// publishes a completion status to the Amazon Simple Notification Service (Amazon +// SNS) topic that you specify in NotificationChannel . To get the results of the +// text analysis operation, first check that the status value published to the +// Amazon SNS topic is SUCCEEDED. If the status is SUCCEEDED you can call either +// GetLendingAnalysis or GetLendingAnalysisSummary and provide the JobId to obtain +// the results of the analysis. +// +// If using OutputConfig to specify an Amazon S3 bucket, the output will be +// contained within the specified prefix in a directory labeled with the job-id. In +// the directory there are 3 sub-directories: +// +// - detailedResponse (contains the GetLendingAnalysis response) +// +// - summaryResponse (for the GetLendingAnalysisSummary response) +// +// - splitDocuments (documents split across logical boundaries) +func (c *Client) StartLendingAnalysis(ctx context.Context, params *StartLendingAnalysisInput, optFns ...func(*Options)) (*StartLendingAnalysisOutput, error) { + if params == nil { + params = &StartLendingAnalysisInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartLendingAnalysis", params, optFns, c.addOperationStartLendingAnalysisMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartLendingAnalysisOutput) + out.ResultMetadata = metadata + return out, nil +} + +type StartLendingAnalysisInput struct { + + // The Amazon S3 bucket that contains the document to be processed. It's used by + // asynchronous operations. + // + // The input document can be an image file in JPEG or PNG format. It can also be a + // file in PDF format. + // + // This member is required. + DocumentLocation *types.DocumentLocation + + // The idempotent token that you use to identify the start request. If you use the + // same token with multiple StartLendingAnalysis requests, the same JobId is + // returned. Use ClientRequestToken to prevent the same job from being + // accidentally started more than once. For more information, see [Calling Amazon Textract Asynchronous Operations]. + // + // [Calling Amazon Textract Asynchronous Operations]: https://docs.aws.amazon.com/textract/latest/dg/api-sync.html + ClientRequestToken *string + + // An identifier that you specify to be included in the completion notification + // published to the Amazon SNS topic. For example, you can use JobTag to identify + // the type of document that the completion notification corresponds to (such as a + // tax form or a receipt). + JobTag *string + + // The KMS key used to encrypt the inference results. This can be in either Key ID + // or Key Alias format. When a KMS key is provided, the KMS key will be used for + // server-side encryption of the objects in the customer bucket. When this + // parameter is not enabled, the result will be encrypted server side, using + // SSE-S3. + KMSKeyId *string + + // The Amazon Simple Notification Service (Amazon SNS) topic to which Amazon + // Textract publishes the completion status of an asynchronous document operation. + NotificationChannel *types.NotificationChannel + + // Sets whether or not your output will go to a user created bucket. Used to set + // the name of the bucket, and the prefix on the output file. + // + // OutputConfig is an optional parameter which lets you adjust where your output + // will be placed. By default, Amazon Textract will store the results internally + // and can only be accessed by the Get API operations. With OutputConfig enabled, + // you can set the name of the bucket the output will be sent to the file prefix of + // the results where you can download your results. Additionally, you can set the + // KMSKeyID parameter to a customer master key (CMK) to encrypt your output. + // Without this parameter set Amazon Textract will encrypt server-side using the + // AWS managed CMK for Amazon S3. + // + // Decryption of Customer Content is necessary for processing of the documents by + // Amazon Textract. If your account is opted out under an AI services opt out + // policy then all unencrypted Customer Content is immediately and permanently + // deleted after the Customer Content has been processed by the service. No copy of + // of the output is retained by Amazon Textract. For information about how to opt + // out, see [Managing AI services opt-out policy.] + // + // For more information on data privacy, see the [Data Privacy FAQ]. + // + // [Managing AI services opt-out policy.]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html + // [Data Privacy FAQ]: https://aws.amazon.com/compliance/data-privacy-faq/ + OutputConfig *types.OutputConfig + + noSmithyDocumentSerde +} + +type StartLendingAnalysisOutput struct { + + // A unique identifier for the lending or text-detection job. The JobId is + // returned from StartLendingAnalysis . A JobId value is only valid for 7 days. + JobId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartLendingAnalysisMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartLendingAnalysis{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartLendingAnalysis{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartLendingAnalysis"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartLendingAnalysisValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartLendingAnalysis(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartLendingAnalysis(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartLendingAnalysis", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_TagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_TagResource.go new file mode 100644 index 00000000..4cc35e94 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_TagResource.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Adds one or more tags to the specified resource. +func (c *Client) TagResource(ctx context.Context, params *TagResourceInput, optFns ...func(*Options)) (*TagResourceOutput, error) { + if params == nil { + params = &TagResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "TagResource", params, optFns, c.addOperationTagResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*TagResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type TagResourceInput struct { + + // The Amazon Resource Name (ARN) that specifies the resource to be tagged. + // + // This member is required. + ResourceARN *string + + // A set of tags (key-value pairs) that you want to assign to the resource. + // + // This member is required. + Tags map[string]string + + noSmithyDocumentSerde +} + +type TagResourceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpTagResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpTagResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "TagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpTagResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "TagResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UntagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UntagResource.go new file mode 100644 index 00000000..8626efbf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UntagResource.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Removes any tags with the specified keys from the specified resource. +func (c *Client) UntagResource(ctx context.Context, params *UntagResourceInput, optFns ...func(*Options)) (*UntagResourceOutput, error) { + if params == nil { + params = &UntagResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UntagResource", params, optFns, c.addOperationUntagResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UntagResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UntagResourceInput struct { + + // The Amazon Resource Name (ARN) that specifies the resource to be untagged. + // + // This member is required. + ResourceARN *string + + // Specifies the tags to be removed from the resource specified by the ResourceARN. + // + // This member is required. + TagKeys []string + + noSmithyDocumentSerde +} + +type UntagResourceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUntagResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUntagResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UntagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUntagResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUntagResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UntagResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UpdateAdapter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UpdateAdapter.go new file mode 100644 index 00000000..3224671f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/api_op_UpdateAdapter.go @@ -0,0 +1,186 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Update the configuration for an adapter. FeatureTypes configurations cannot be +// updated. At least one new parameter must be specified as an argument. +func (c *Client) UpdateAdapter(ctx context.Context, params *UpdateAdapterInput, optFns ...func(*Options)) (*UpdateAdapterOutput, error) { + if params == nil { + params = &UpdateAdapterInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateAdapter", params, optFns, c.addOperationUpdateAdapterMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateAdapterOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateAdapterInput struct { + + // A string containing a unique ID for the adapter that will be updated. + // + // This member is required. + AdapterId *string + + // The new name to be applied to the adapter. + AdapterName *string + + // The new auto-update status to be applied to the adapter. + AutoUpdate types.AutoUpdate + + // The new description to be applied to the adapter. + Description *string + + noSmithyDocumentSerde +} + +type UpdateAdapterOutput struct { + + // A string containing a unique ID for the adapter that has been updated. + AdapterId *string + + // A string containing the name of the adapter that has been updated. + AdapterName *string + + // The auto-update status of the adapter that has been updated. + AutoUpdate types.AutoUpdate + + // An object specifying the creation time of the the adapter that has been updated. + CreationTime *time.Time + + // A string containing the description of the adapter that has been updated. + Description *string + + // List of the targeted feature types for the updated adapter. + FeatureTypes []types.FeatureType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateAdapterMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateAdapter{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateAdapter{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateAdapter"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateAdapterValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateAdapter(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateAdapter(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateAdapter", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/auth.go new file mode 100644 index 00000000..3009b9db --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/auth.go @@ -0,0 +1,313 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { + params.Region = options.Region +} + +type setLegacyContextSigningOptionsMiddleware struct { +} + +func (*setLegacyContextSigningOptionsMiddleware) ID() string { + return "setLegacyContextSigningOptions" +} + +func (m *setLegacyContextSigningOptionsMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + rscheme := getResolvedAuthScheme(ctx) + schemeID := rscheme.Scheme.SchemeID() + + if sn := awsmiddleware.GetSigningName(ctx); sn != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningName(&rscheme.SignerProperties, sn) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningName(&rscheme.SignerProperties, sn) + } + } + + if sr := awsmiddleware.GetSigningRegion(ctx); sr != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningRegion(&rscheme.SignerProperties, sr) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningRegions(&rscheme.SignerProperties, []string{sr}) + } + } + + return next.HandleFinalize(ctx, in) +} + +func addSetLegacyContextSigningOptionsMiddleware(stack *middleware.Stack) error { + return stack.Finalize.Insert(&setLegacyContextSigningOptionsMiddleware{}, "Signing", middleware.Before) +} + +type withAnonymous struct { + resolver AuthSchemeResolver +} + +var _ AuthSchemeResolver = (*withAnonymous)(nil) + +func (v *withAnonymous) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + opts, err := v.resolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return nil, err + } + + opts = append(opts, &smithyauth.Option{ + SchemeID: smithyauth.SchemeIDAnonymous, + }) + return opts, nil +} + +func wrapWithAnonymousAuth(options *Options) { + if _, ok := options.AuthSchemeResolver.(*defaultAuthSchemeResolver); !ok { + return + } + + options.AuthSchemeResolver = &withAnonymous{ + resolver: options.AuthSchemeResolver, + } +} + +// AuthResolverParameters contains the set of inputs necessary for auth scheme +// resolution. +type AuthResolverParameters struct { + // The name of the operation being invoked. + Operation string + + // The region in which the operation is being invoked. + Region string +} + +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { + params := &AuthResolverParameters{ + Operation: operation, + } + + bindAuthParamsRegion(ctx, params, input, options) + + return params +} + +// AuthSchemeResolver returns a set of possible authentication options for an +// operation. +type AuthSchemeResolver interface { + ResolveAuthSchemes(context.Context, *AuthResolverParameters) ([]*smithyauth.Option, error) +} + +type defaultAuthSchemeResolver struct{} + +var _ AuthSchemeResolver = (*defaultAuthSchemeResolver)(nil) + +func (*defaultAuthSchemeResolver) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + if overrides, ok := operationAuthOptions[params.Operation]; ok { + return overrides(params), nil + } + return serviceAuthOptions(params), nil +} + +var operationAuthOptions = map[string]func(*AuthResolverParameters) []*smithyauth.Option{} + +func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + { + SchemeID: smithyauth.SchemeIDSigV4, + SignerProperties: func() smithy.Properties { + var props smithy.Properties + smithyhttp.SetSigV4SigningName(&props, "textract") + smithyhttp.SetSigV4SigningRegion(&props, params.Region) + return props + }(), + }, + } +} + +type resolveAuthSchemeMiddleware struct { + operation string + options Options +} + +func (*resolveAuthSchemeMiddleware) ID() string { + return "ResolveAuthScheme" +} + +func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") + defer span.End() + + params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) + } + + scheme, ok := m.selectScheme(options) + if !ok { + return out, metadata, fmt.Errorf("could not select an auth scheme") + } + + ctx = setResolvedAuthScheme(ctx, scheme) + + span.SetProperty("auth.scheme_id", scheme.Scheme.SchemeID()) + span.End() + return next.HandleFinalize(ctx, in) +} + +func (m *resolveAuthSchemeMiddleware) selectScheme(options []*smithyauth.Option) (*resolvedAuthScheme, bool) { + for _, option := range options { + if option.SchemeID == smithyauth.SchemeIDAnonymous { + return newResolvedAuthScheme(smithyhttp.NewAnonymousScheme(), option), true + } + + for _, scheme := range m.options.AuthSchemes { + if scheme.SchemeID() != option.SchemeID { + continue + } + + if scheme.IdentityResolver(m.options) != nil { + return newResolvedAuthScheme(scheme, option), true + } + } + } + + return nil, false +} + +type resolvedAuthSchemeKey struct{} + +type resolvedAuthScheme struct { + Scheme smithyhttp.AuthScheme + IdentityProperties smithy.Properties + SignerProperties smithy.Properties +} + +func newResolvedAuthScheme(scheme smithyhttp.AuthScheme, option *smithyauth.Option) *resolvedAuthScheme { + return &resolvedAuthScheme{ + Scheme: scheme, + IdentityProperties: option.IdentityProperties, + SignerProperties: option.SignerProperties, + } +} + +func setResolvedAuthScheme(ctx context.Context, scheme *resolvedAuthScheme) context.Context { + return middleware.WithStackValue(ctx, resolvedAuthSchemeKey{}, scheme) +} + +func getResolvedAuthScheme(ctx context.Context) *resolvedAuthScheme { + v, _ := middleware.GetStackValue(ctx, resolvedAuthSchemeKey{}).(*resolvedAuthScheme) + return v +} + +type getIdentityMiddleware struct { + options Options +} + +func (*getIdentityMiddleware) ID() string { + return "GetIdentity" +} + +func (m *getIdentityMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + innerCtx, span := tracing.StartSpan(ctx, "GetIdentity") + defer span.End() + + rscheme := getResolvedAuthScheme(innerCtx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + resolver := rscheme.Scheme.IdentityResolver(m.options) + if resolver == nil { + return out, metadata, fmt.Errorf("no identity resolver") + } + + identity, err := timeOperationMetric(ctx, "client.call.resolve_identity_duration", + func() (smithyauth.Identity, error) { + return resolver.GetIdentity(innerCtx, rscheme.IdentityProperties) + }, + func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("get identity: %w", err) + } + + ctx = setIdentity(ctx, identity) + + span.End() + return next.HandleFinalize(ctx, in) +} + +type identityKey struct{} + +func setIdentity(ctx context.Context, identity smithyauth.Identity) context.Context { + return middleware.WithStackValue(ctx, identityKey{}, identity) +} + +func getIdentity(ctx context.Context) smithyauth.Identity { + v, _ := middleware.GetStackValue(ctx, identityKey{}).(smithyauth.Identity) + return v +} + +type signRequestMiddleware struct { + options Options +} + +func (*signRequestMiddleware) ID() string { + return "Signing" +} + +func (m *signRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "SignRequest") + defer span.End() + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unexpected transport type %T", in.Request) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + identity := getIdentity(ctx) + if identity == nil { + return out, metadata, fmt.Errorf("no identity") + } + + signer := rscheme.Scheme.Signer() + if signer == nil { + return out, metadata, fmt.Errorf("no signer") + } + + _, err = timeOperationMetric(ctx, "client.call.signing_duration", func() (any, error) { + return nil, signer.SignRequest(ctx, req, identity, rscheme.SignerProperties) + }, func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("sign request: %w", err) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/deserializers.go new file mode 100644 index 00000000..5ec14e45 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/deserializers.go @@ -0,0 +1,10173 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + smithy "github.com/aws/smithy-go" + smithyio "github.com/aws/smithy-go/io" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + smithytime "github.com/aws/smithy-go/time" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "io" + "math" + "strings" + "time" +) + +func deserializeS3Expires(v string) (*time.Time, error) { + t, err := smithytime.ParseHTTPDate(v) + if err != nil { + return nil, nil + } + return &t, nil +} + +type awsAwsjson11_deserializeOpAnalyzeDocument struct { +} + +func (*awsAwsjson11_deserializeOpAnalyzeDocument) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAnalyzeDocument) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAnalyzeDocument(response, &metadata) + } + output := &AnalyzeDocumentOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAnalyzeDocumentOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAnalyzeDocument(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("HumanLoopQuotaExceededException", errorCode): + return awsAwsjson11_deserializeErrorHumanLoopQuotaExceededException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAnalyzeExpense struct { +} + +func (*awsAwsjson11_deserializeOpAnalyzeExpense) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAnalyzeExpense) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAnalyzeExpense(response, &metadata) + } + output := &AnalyzeExpenseOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAnalyzeExpenseOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAnalyzeExpense(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAnalyzeID struct { +} + +func (*awsAwsjson11_deserializeOpAnalyzeID) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAnalyzeID) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAnalyzeID(response, &metadata) + } + output := &AnalyzeIDOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAnalyzeIDOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAnalyzeID(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateAdapter struct { +} + +func (*awsAwsjson11_deserializeOpCreateAdapter) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateAdapter) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateAdapter(response, &metadata) + } + output := &CreateAdapterOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateAdapterOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateAdapter(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("ConflictException", errorCode): + return awsAwsjson11_deserializeErrorConflictException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ServiceQuotaExceededException", errorCode): + return awsAwsjson11_deserializeErrorServiceQuotaExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateAdapterVersion struct { +} + +func (*awsAwsjson11_deserializeOpCreateAdapterVersion) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateAdapterVersion) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateAdapterVersion(response, &metadata) + } + output := &CreateAdapterVersionOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateAdapterVersionOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateAdapterVersion(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("ConflictException", errorCode): + return awsAwsjson11_deserializeErrorConflictException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ServiceQuotaExceededException", errorCode): + return awsAwsjson11_deserializeErrorServiceQuotaExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteAdapter struct { +} + +func (*awsAwsjson11_deserializeOpDeleteAdapter) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteAdapter) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteAdapter(response, &metadata) + } + output := &DeleteAdapterOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteAdapterOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteAdapter(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("ConflictException", errorCode): + return awsAwsjson11_deserializeErrorConflictException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteAdapterVersion struct { +} + +func (*awsAwsjson11_deserializeOpDeleteAdapterVersion) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteAdapterVersion) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteAdapterVersion(response, &metadata) + } + output := &DeleteAdapterVersionOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteAdapterVersionOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteAdapterVersion(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("ConflictException", errorCode): + return awsAwsjson11_deserializeErrorConflictException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDetectDocumentText struct { +} + +func (*awsAwsjson11_deserializeOpDetectDocumentText) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDetectDocumentText) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDetectDocumentText(response, &metadata) + } + output := &DetectDocumentTextOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDetectDocumentTextOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDetectDocumentText(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetAdapter struct { +} + +func (*awsAwsjson11_deserializeOpGetAdapter) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetAdapter) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetAdapter(response, &metadata) + } + output := &GetAdapterOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetAdapterOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetAdapter(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetAdapterVersion struct { +} + +func (*awsAwsjson11_deserializeOpGetAdapterVersion) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetAdapterVersion) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetAdapterVersion(response, &metadata) + } + output := &GetAdapterVersionOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetAdapterVersionOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetAdapterVersion(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetDocumentAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpGetDocumentAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetDocumentAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetDocumentAnalysis(response, &metadata) + } + output := &GetDocumentAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetDocumentAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetDocumentAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidJobIdException", errorCode): + return awsAwsjson11_deserializeErrorInvalidJobIdException(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetDocumentTextDetection struct { +} + +func (*awsAwsjson11_deserializeOpGetDocumentTextDetection) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetDocumentTextDetection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetDocumentTextDetection(response, &metadata) + } + output := &GetDocumentTextDetectionOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetDocumentTextDetectionOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetDocumentTextDetection(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidJobIdException", errorCode): + return awsAwsjson11_deserializeErrorInvalidJobIdException(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetExpenseAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpGetExpenseAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetExpenseAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetExpenseAnalysis(response, &metadata) + } + output := &GetExpenseAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetExpenseAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetExpenseAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidJobIdException", errorCode): + return awsAwsjson11_deserializeErrorInvalidJobIdException(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetLendingAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpGetLendingAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetLendingAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetLendingAnalysis(response, &metadata) + } + output := &GetLendingAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetLendingAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetLendingAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidJobIdException", errorCode): + return awsAwsjson11_deserializeErrorInvalidJobIdException(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetLendingAnalysisSummary struct { +} + +func (*awsAwsjson11_deserializeOpGetLendingAnalysisSummary) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetLendingAnalysisSummary) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetLendingAnalysisSummary(response, &metadata) + } + output := &GetLendingAnalysisSummaryOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetLendingAnalysisSummaryOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetLendingAnalysisSummary(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidJobIdException", errorCode): + return awsAwsjson11_deserializeErrorInvalidJobIdException(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListAdapters struct { +} + +func (*awsAwsjson11_deserializeOpListAdapters) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListAdapters) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListAdapters(response, &metadata) + } + output := &ListAdaptersOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListAdaptersOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListAdapters(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListAdapterVersions struct { +} + +func (*awsAwsjson11_deserializeOpListAdapterVersions) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListAdapterVersions) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListAdapterVersions(response, &metadata) + } + output := &ListAdapterVersionsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListAdapterVersionsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListAdapterVersions(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListTagsForResource struct { +} + +func (*awsAwsjson11_deserializeOpListTagsForResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListTagsForResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListTagsForResource(response, &metadata) + } + output := &ListTagsForResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartDocumentAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpStartDocumentAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartDocumentAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartDocumentAnalysis(response, &metadata) + } + output := &StartDocumentAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartDocumentAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartDocumentAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartDocumentTextDetection struct { +} + +func (*awsAwsjson11_deserializeOpStartDocumentTextDetection) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartDocumentTextDetection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartDocumentTextDetection(response, &metadata) + } + output := &StartDocumentTextDetectionOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartDocumentTextDetectionOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartDocumentTextDetection(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartExpenseAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpStartExpenseAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartExpenseAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartExpenseAnalysis(response, &metadata) + } + output := &StartExpenseAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartExpenseAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartExpenseAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartLendingAnalysis struct { +} + +func (*awsAwsjson11_deserializeOpStartLendingAnalysis) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartLendingAnalysis) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartLendingAnalysis(response, &metadata) + } + output := &StartLendingAnalysisOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartLendingAnalysisOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartLendingAnalysis(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("BadDocumentException", errorCode): + return awsAwsjson11_deserializeErrorBadDocumentException(response, errorBody) + + case strings.EqualFold("DocumentTooLargeException", errorCode): + return awsAwsjson11_deserializeErrorDocumentTooLargeException(response, errorBody) + + case strings.EqualFold("IdempotentParameterMismatchException", errorCode): + return awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidKMSKeyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidKMSKeyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidS3ObjectException", errorCode): + return awsAwsjson11_deserializeErrorInvalidS3ObjectException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("UnsupportedDocumentException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedDocumentException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpTagResource struct { +} + +func (*awsAwsjson11_deserializeOpTagResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorTagResource(response, &metadata) + } + output := &TagResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentTagResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ServiceQuotaExceededException", errorCode): + return awsAwsjson11_deserializeErrorServiceQuotaExceededException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUntagResource struct { +} + +func (*awsAwsjson11_deserializeOpUntagResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUntagResource(response, &metadata) + } + output := &UntagResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUntagResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateAdapter struct { +} + +func (*awsAwsjson11_deserializeOpUpdateAdapter) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateAdapter) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateAdapter(response, &metadata) + } + output := &UpdateAdapterOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateAdapterOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateAdapter(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsAwsjson11_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("ConflictException", errorCode): + return awsAwsjson11_deserializeErrorConflictException(response, errorBody) + + case strings.EqualFold("InternalServerError", errorCode): + return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ProvisionedThroughputExceededException", errorCode): + return awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ThrottlingException", errorCode): + return awsAwsjson11_deserializeErrorThrottlingException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +func awsAwsjson11_deserializeErrorAccessDeniedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.AccessDeniedException{} + err := awsAwsjson11_deserializeDocumentAccessDeniedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorBadDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.BadDocumentException{} + err := awsAwsjson11_deserializeDocumentBadDocumentException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorConflictException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ConflictException{} + err := awsAwsjson11_deserializeDocumentConflictException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorDocumentTooLargeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.DocumentTooLargeException{} + err := awsAwsjson11_deserializeDocumentDocumentTooLargeException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorHumanLoopQuotaExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.HumanLoopQuotaExceededException{} + err := awsAwsjson11_deserializeDocumentHumanLoopQuotaExceededException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorIdempotentParameterMismatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.IdempotentParameterMismatchException{} + err := awsAwsjson11_deserializeDocumentIdempotentParameterMismatchException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInternalServerError(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InternalServerError{} + err := awsAwsjson11_deserializeDocumentInternalServerError(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidJobIdException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidJobIdException{} + err := awsAwsjson11_deserializeDocumentInvalidJobIdException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidKMSKeyException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidKMSKeyException{} + err := awsAwsjson11_deserializeDocumentInvalidKMSKeyException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidParameterException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidParameterException{} + err := awsAwsjson11_deserializeDocumentInvalidParameterException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidS3ObjectException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidS3ObjectException{} + err := awsAwsjson11_deserializeDocumentInvalidS3ObjectException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorLimitExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.LimitExceededException{} + err := awsAwsjson11_deserializeDocumentLimitExceededException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorProvisionedThroughputExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ProvisionedThroughputExceededException{} + err := awsAwsjson11_deserializeDocumentProvisionedThroughputExceededException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorResourceNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ResourceNotFoundException{} + err := awsAwsjson11_deserializeDocumentResourceNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorServiceQuotaExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ServiceQuotaExceededException{} + err := awsAwsjson11_deserializeDocumentServiceQuotaExceededException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorThrottlingException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ThrottlingException{} + err := awsAwsjson11_deserializeDocumentThrottlingException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnsupportedDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnsupportedDocumentException{} + err := awsAwsjson11_deserializeDocumentUnsupportedDocumentException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorValidationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ValidationException{} + err := awsAwsjson11_deserializeDocumentValidationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeDocumentAccessDeniedException(v **types.AccessDeniedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccessDeniedException + if *v == nil { + sv = &types.AccessDeniedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterList(v *[]types.AdapterOverview, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AdapterOverview + if *v == nil { + cv = []types.AdapterOverview{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AdapterOverview + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAdapterOverview(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterOverview(v **types.AdapterOverview, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdapterOverview + if *v == nil { + sv = &types.AdapterOverview{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterName to be of type string, got %T instead", value) + } + sv.AdapterName = ptr.String(jtv) + } + + case "CreationTime": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) + + } + } + + case "FeatureTypes": + if err := awsAwsjson11_deserializeDocumentFeatureTypes(&sv.FeatureTypes, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterVersionDatasetConfig(v **types.AdapterVersionDatasetConfig, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdapterVersionDatasetConfig + if *v == nil { + sv = &types.AdapterVersionDatasetConfig{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ManifestS3Object": + if err := awsAwsjson11_deserializeDocumentS3Object(&sv.ManifestS3Object, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterVersionEvaluationMetric(v **types.AdapterVersionEvaluationMetric, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdapterVersionEvaluationMetric + if *v == nil { + sv = &types.AdapterVersionEvaluationMetric{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterVersion": + if err := awsAwsjson11_deserializeDocumentEvaluationMetric(&sv.AdapterVersion, value); err != nil { + return err + } + + case "Baseline": + if err := awsAwsjson11_deserializeDocumentEvaluationMetric(&sv.Baseline, value); err != nil { + return err + } + + case "FeatureType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FeatureType to be of type string, got %T instead", value) + } + sv.FeatureType = types.FeatureType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterVersionEvaluationMetrics(v *[]types.AdapterVersionEvaluationMetric, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AdapterVersionEvaluationMetric + if *v == nil { + cv = []types.AdapterVersionEvaluationMetric{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AdapterVersionEvaluationMetric + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAdapterVersionEvaluationMetric(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterVersionList(v *[]types.AdapterVersionOverview, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AdapterVersionOverview + if *v == nil { + cv = []types.AdapterVersionOverview{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AdapterVersionOverview + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAdapterVersionOverview(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAdapterVersionOverview(v **types.AdapterVersionOverview, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdapterVersionOverview + if *v == nil { + sv = &types.AdapterVersionOverview{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersion to be of type string, got %T instead", value) + } + sv.AdapterVersion = ptr.String(jtv) + } + + case "CreationTime": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) + + } + } + + case "FeatureTypes": + if err := awsAwsjson11_deserializeDocumentFeatureTypes(&sv.FeatureTypes, value); err != nil { + return err + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersionStatus to be of type string, got %T instead", value) + } + sv.Status = types.AdapterVersionStatus(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersionStatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAnalyzeIDDetections(v **types.AnalyzeIDDetections, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AnalyzeIDDetections + if *v == nil { + sv = &types.AnalyzeIDDetections{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "NormalizedValue": + if err := awsAwsjson11_deserializeDocumentNormalizedValue(&sv.NormalizedValue, value); err != nil { + return err + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentBadDocumentException(v **types.BadDocumentException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.BadDocumentException + if *v == nil { + sv = &types.BadDocumentException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentBlock(v **types.Block, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Block + if *v == nil { + sv = &types.Block{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "BlockType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected BlockType to be of type string, got %T instead", value) + } + sv.BlockType = types.BlockType(jtv) + } + + case "ColumnIndex": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ColumnIndex = ptr.Int32(int32(i64)) + } + + case "ColumnSpan": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ColumnSpan = ptr.Int32(int32(i64)) + } + + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "EntityTypes": + if err := awsAwsjson11_deserializeDocumentEntityTypes(&sv.EntityTypes, value); err != nil { + return err + } + + case "Geometry": + if err := awsAwsjson11_deserializeDocumentGeometry(&sv.Geometry, value); err != nil { + return err + } + + case "Id": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NonEmptyString to be of type string, got %T instead", value) + } + sv.Id = ptr.String(jtv) + } + + case "Page": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Page = ptr.Int32(int32(i64)) + } + + case "Query": + if err := awsAwsjson11_deserializeDocumentQuery(&sv.Query, value); err != nil { + return err + } + + case "Relationships": + if err := awsAwsjson11_deserializeDocumentRelationshipList(&sv.Relationships, value); err != nil { + return err + } + + case "RowIndex": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.RowIndex = ptr.Int32(int32(i64)) + } + + case "RowSpan": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.RowSpan = ptr.Int32(int32(i64)) + } + + case "SelectionStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SelectionStatus to be of type string, got %T instead", value) + } + sv.SelectionStatus = types.SelectionStatus(jtv) + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + case "TextType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TextType to be of type string, got %T instead", value) + } + sv.TextType = types.TextType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentBlockList(v *[]types.Block, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Block + if *v == nil { + cv = []types.Block{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Block + destAddr := &col + if err := awsAwsjson11_deserializeDocumentBlock(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentBoundingBox(v **types.BoundingBox, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.BoundingBox + if *v == nil { + sv = &types.BoundingBox{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Height": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Height = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Height = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Left": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Left = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Left = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Top": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Top = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Top = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Width": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Width = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Width = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentConflictException(v **types.ConflictException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ConflictException + if *v == nil { + sv = &types.ConflictException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDetectedSignature(v **types.DetectedSignature, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DetectedSignature + if *v == nil { + sv = &types.DetectedSignature{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Page": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Page = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDetectedSignatureList(v *[]types.DetectedSignature, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.DetectedSignature + if *v == nil { + cv = []types.DetectedSignature{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.DetectedSignature + destAddr := &col + if err := awsAwsjson11_deserializeDocumentDetectedSignature(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentDocumentGroup(v **types.DocumentGroup, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DocumentGroup + if *v == nil { + sv = &types.DocumentGroup{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DetectedSignatures": + if err := awsAwsjson11_deserializeDocumentDetectedSignatureList(&sv.DetectedSignatures, value); err != nil { + return err + } + + case "SplitDocuments": + if err := awsAwsjson11_deserializeDocumentSplitDocumentList(&sv.SplitDocuments, value); err != nil { + return err + } + + case "Type": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NonEmptyString to be of type string, got %T instead", value) + } + sv.Type = ptr.String(jtv) + } + + case "UndetectedSignatures": + if err := awsAwsjson11_deserializeDocumentUndetectedSignatureList(&sv.UndetectedSignatures, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDocumentGroupList(v *[]types.DocumentGroup, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.DocumentGroup + if *v == nil { + cv = []types.DocumentGroup{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.DocumentGroup + destAddr := &col + if err := awsAwsjson11_deserializeDocumentDocumentGroup(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentDocumentMetadata(v **types.DocumentMetadata, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DocumentMetadata + if *v == nil { + sv = &types.DocumentMetadata{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Pages": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Pages = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDocumentTooLargeException(v **types.DocumentTooLargeException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DocumentTooLargeException + if *v == nil { + sv = &types.DocumentTooLargeException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEntityTypes(v *[]types.EntityType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.EntityType + if *v == nil { + cv = []types.EntityType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.EntityType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EntityType to be of type string, got %T instead", value) + } + col = types.EntityType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentEvaluationMetric(v **types.EvaluationMetric, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EvaluationMetric + if *v == nil { + sv = &types.EvaluationMetric{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "F1Score": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.F1Score = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.F1Score = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Precision": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Precision = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Precision = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Recall": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Recall = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Recall = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseCurrency(v **types.ExpenseCurrency, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseCurrency + if *v == nil { + sv = &types.ExpenseCurrency{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseDetection(v **types.ExpenseDetection, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseDetection + if *v == nil { + sv = &types.ExpenseDetection{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "Geometry": + if err := awsAwsjson11_deserializeDocumentGeometry(&sv.Geometry, value); err != nil { + return err + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseDocument(v **types.ExpenseDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseDocument + if *v == nil { + sv = &types.ExpenseDocument{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "ExpenseIndex": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ExpenseIndex = ptr.Int32(int32(i64)) + } + + case "LineItemGroups": + if err := awsAwsjson11_deserializeDocumentLineItemGroupList(&sv.LineItemGroups, value); err != nil { + return err + } + + case "SummaryFields": + if err := awsAwsjson11_deserializeDocumentExpenseFieldList(&sv.SummaryFields, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseDocumentList(v *[]types.ExpenseDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ExpenseDocument + if *v == nil { + cv = []types.ExpenseDocument{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ExpenseDocument + destAddr := &col + if err := awsAwsjson11_deserializeDocumentExpenseDocument(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseField(v **types.ExpenseField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseField + if *v == nil { + sv = &types.ExpenseField{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Currency": + if err := awsAwsjson11_deserializeDocumentExpenseCurrency(&sv.Currency, value); err != nil { + return err + } + + case "GroupProperties": + if err := awsAwsjson11_deserializeDocumentExpenseGroupPropertyList(&sv.GroupProperties, value); err != nil { + return err + } + + case "LabelDetection": + if err := awsAwsjson11_deserializeDocumentExpenseDetection(&sv.LabelDetection, value); err != nil { + return err + } + + case "PageNumber": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.PageNumber = ptr.Int32(int32(i64)) + } + + case "Type": + if err := awsAwsjson11_deserializeDocumentExpenseType(&sv.Type, value); err != nil { + return err + } + + case "ValueDetection": + if err := awsAwsjson11_deserializeDocumentExpenseDetection(&sv.ValueDetection, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseFieldList(v *[]types.ExpenseField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ExpenseField + if *v == nil { + cv = []types.ExpenseField{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ExpenseField + destAddr := &col + if err := awsAwsjson11_deserializeDocumentExpenseField(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseGroupProperty(v **types.ExpenseGroupProperty, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseGroupProperty + if *v == nil { + sv = &types.ExpenseGroupProperty{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Id": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Id = ptr.String(jtv) + } + + case "Types": + if err := awsAwsjson11_deserializeDocumentStringList(&sv.Types, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseGroupPropertyList(v *[]types.ExpenseGroupProperty, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ExpenseGroupProperty + if *v == nil { + cv = []types.ExpenseGroupProperty{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ExpenseGroupProperty + destAddr := &col + if err := awsAwsjson11_deserializeDocumentExpenseGroupProperty(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentExpenseType(v **types.ExpenseType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpenseType + if *v == nil { + sv = &types.ExpenseType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExtraction(v **types.Extraction, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Extraction + if *v == nil { + sv = &types.Extraction{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ExpenseDocument": + if err := awsAwsjson11_deserializeDocumentExpenseDocument(&sv.ExpenseDocument, value); err != nil { + return err + } + + case "IdentityDocument": + if err := awsAwsjson11_deserializeDocumentIdentityDocument(&sv.IdentityDocument, value); err != nil { + return err + } + + case "LendingDocument": + if err := awsAwsjson11_deserializeDocumentLendingDocument(&sv.LendingDocument, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExtractionList(v *[]types.Extraction, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Extraction + if *v == nil { + cv = []types.Extraction{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Extraction + destAddr := &col + if err := awsAwsjson11_deserializeDocumentExtraction(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentFeatureTypes(v *[]types.FeatureType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.FeatureType + if *v == nil { + cv = []types.FeatureType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.FeatureType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FeatureType to be of type string, got %T instead", value) + } + col = types.FeatureType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentGeometry(v **types.Geometry, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Geometry + if *v == nil { + sv = &types.Geometry{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "BoundingBox": + if err := awsAwsjson11_deserializeDocumentBoundingBox(&sv.BoundingBox, value); err != nil { + return err + } + + case "Polygon": + if err := awsAwsjson11_deserializeDocumentPolygon(&sv.Polygon, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentHumanLoopActivationOutput(v **types.HumanLoopActivationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.HumanLoopActivationOutput + if *v == nil { + sv = &types.HumanLoopActivationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "HumanLoopActivationConditionsEvaluationResults": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SynthesizedJsonHumanLoopActivationConditionsEvaluationResults to be of type string, got %T instead", value) + } + sv.HumanLoopActivationConditionsEvaluationResults = ptr.String(jtv) + } + + case "HumanLoopActivationReasons": + if err := awsAwsjson11_deserializeDocumentHumanLoopActivationReasons(&sv.HumanLoopActivationReasons, value); err != nil { + return err + } + + case "HumanLoopArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected HumanLoopArn to be of type string, got %T instead", value) + } + sv.HumanLoopArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentHumanLoopActivationReasons(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected HumanLoopActivationReason to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentHumanLoopQuotaExceededException(v **types.HumanLoopQuotaExceededException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.HumanLoopQuotaExceededException + if *v == nil { + sv = &types.HumanLoopQuotaExceededException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + case "QuotaCode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.QuotaCode = ptr.String(jtv) + } + + case "ResourceType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.ResourceType = ptr.String(jtv) + } + + case "ServiceCode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.ServiceCode = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdempotentParameterMismatchException(v **types.IdempotentParameterMismatchException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.IdempotentParameterMismatchException + if *v == nil { + sv = &types.IdempotentParameterMismatchException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdentityDocument(v **types.IdentityDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.IdentityDocument + if *v == nil { + sv = &types.IdentityDocument{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "DocumentIndex": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.DocumentIndex = ptr.Int32(int32(i64)) + } + + case "IdentityDocumentFields": + if err := awsAwsjson11_deserializeDocumentIdentityDocumentFieldList(&sv.IdentityDocumentFields, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdentityDocumentField(v **types.IdentityDocumentField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.IdentityDocumentField + if *v == nil { + sv = &types.IdentityDocumentField{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Type": + if err := awsAwsjson11_deserializeDocumentAnalyzeIDDetections(&sv.Type, value); err != nil { + return err + } + + case "ValueDetection": + if err := awsAwsjson11_deserializeDocumentAnalyzeIDDetections(&sv.ValueDetection, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdentityDocumentFieldList(v *[]types.IdentityDocumentField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.IdentityDocumentField + if *v == nil { + cv = []types.IdentityDocumentField{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.IdentityDocumentField + destAddr := &col + if err := awsAwsjson11_deserializeDocumentIdentityDocumentField(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentIdentityDocumentList(v *[]types.IdentityDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.IdentityDocument + if *v == nil { + cv = []types.IdentityDocument{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.IdentityDocument + destAddr := &col + if err := awsAwsjson11_deserializeDocumentIdentityDocument(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentIdList(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NonEmptyString to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentInternalServerError(v **types.InternalServerError, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InternalServerError + if *v == nil { + sv = &types.InternalServerError{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidJobIdException(v **types.InvalidJobIdException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidJobIdException + if *v == nil { + sv = &types.InvalidJobIdException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidKMSKeyException(v **types.InvalidKMSKeyException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidKMSKeyException + if *v == nil { + sv = &types.InvalidKMSKeyException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidParameterException(v **types.InvalidParameterException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidParameterException + if *v == nil { + sv = &types.InvalidParameterException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidS3ObjectException(v **types.InvalidS3ObjectException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidS3ObjectException + if *v == nil { + sv = &types.InvalidS3ObjectException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingDetection(v **types.LendingDetection, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LendingDetection + if *v == nil { + sv = &types.LendingDetection{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "Geometry": + if err := awsAwsjson11_deserializeDocumentGeometry(&sv.Geometry, value); err != nil { + return err + } + + case "SelectionStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SelectionStatus to be of type string, got %T instead", value) + } + sv.SelectionStatus = types.SelectionStatus(jtv) + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingDetectionList(v *[]types.LendingDetection, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LendingDetection + if *v == nil { + cv = []types.LendingDetection{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LendingDetection + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLendingDetection(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingDocument(v **types.LendingDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LendingDocument + if *v == nil { + sv = &types.LendingDocument{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LendingFields": + if err := awsAwsjson11_deserializeDocumentLendingFieldList(&sv.LendingFields, value); err != nil { + return err + } + + case "SignatureDetections": + if err := awsAwsjson11_deserializeDocumentSignatureDetectionList(&sv.SignatureDetections, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingField(v **types.LendingField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LendingField + if *v == nil { + sv = &types.LendingField{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "KeyDetection": + if err := awsAwsjson11_deserializeDocumentLendingDetection(&sv.KeyDetection, value); err != nil { + return err + } + + case "Type": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Type = ptr.String(jtv) + } + + case "ValueDetections": + if err := awsAwsjson11_deserializeDocumentLendingDetectionList(&sv.ValueDetections, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingFieldList(v *[]types.LendingField, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LendingField + if *v == nil { + cv = []types.LendingField{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LendingField + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLendingField(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingResult(v **types.LendingResult, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LendingResult + if *v == nil { + sv = &types.LendingResult{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Extractions": + if err := awsAwsjson11_deserializeDocumentExtractionList(&sv.Extractions, value); err != nil { + return err + } + + case "Page": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Page = ptr.Int32(int32(i64)) + } + + case "PageClassification": + if err := awsAwsjson11_deserializeDocumentPageClassification(&sv.PageClassification, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingResultList(v *[]types.LendingResult, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LendingResult + if *v == nil { + cv = []types.LendingResult{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LendingResult + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLendingResult(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLendingSummary(v **types.LendingSummary, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LendingSummary + if *v == nil { + sv = &types.LendingSummary{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DocumentGroups": + if err := awsAwsjson11_deserializeDocumentDocumentGroupList(&sv.DocumentGroups, value); err != nil { + return err + } + + case "UndetectedDocumentTypes": + if err := awsAwsjson11_deserializeDocumentUndetectedDocumentTypeList(&sv.UndetectedDocumentTypes, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExceededException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LimitExceededException + if *v == nil { + sv = &types.LimitExceededException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLineItemFields(v **types.LineItemFields, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LineItemFields + if *v == nil { + sv = &types.LineItemFields{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LineItemExpenseFields": + if err := awsAwsjson11_deserializeDocumentExpenseFieldList(&sv.LineItemExpenseFields, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLineItemGroup(v **types.LineItemGroup, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LineItemGroup + if *v == nil { + sv = &types.LineItemGroup{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LineItemGroupIndex": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.LineItemGroupIndex = ptr.Int32(int32(i64)) + } + + case "LineItems": + if err := awsAwsjson11_deserializeDocumentLineItemList(&sv.LineItems, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLineItemGroupList(v *[]types.LineItemGroup, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LineItemGroup + if *v == nil { + cv = []types.LineItemGroup{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LineItemGroup + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLineItemGroup(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLineItemList(v *[]types.LineItemFields, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LineItemFields + if *v == nil { + cv = []types.LineItemFields{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LineItemFields + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLineItemFields(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentNormalizedValue(v **types.NormalizedValue, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NormalizedValue + if *v == nil { + sv = &types.NormalizedValue{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Value": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Value = ptr.String(jtv) + } + + case "ValueType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ValueType to be of type string, got %T instead", value) + } + sv.ValueType = types.ValueType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentOutputConfig(v **types.OutputConfig, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.OutputConfig + if *v == nil { + sv = &types.OutputConfig{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "S3Bucket": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3Bucket to be of type string, got %T instead", value) + } + sv.S3Bucket = ptr.String(jtv) + } + + case "S3Prefix": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3ObjectName to be of type string, got %T instead", value) + } + sv.S3Prefix = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPageClassification(v **types.PageClassification, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PageClassification + if *v == nil { + sv = &types.PageClassification{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "PageNumber": + if err := awsAwsjson11_deserializeDocumentPredictionList(&sv.PageNumber, value); err != nil { + return err + } + + case "PageType": + if err := awsAwsjson11_deserializeDocumentPredictionList(&sv.PageType, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPageList(v *[]int32, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []int32 + if *v == nil { + cv = []int32{} + } else { + cv = *v + } + + for _, value := range shape { + var col int32 + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + col = int32(i64) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentPages(v *[]int32, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []int32 + if *v == nil { + cv = []int32{} + } else { + cv = *v + } + + for _, value := range shape { + var col int32 + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + col = int32(i64) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentPoint(v **types.Point, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Point + if *v == nil { + sv = &types.Point{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "X": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.X = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.X = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + case "Y": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Y = float32(f64) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Y = float32(f64) + + default: + return fmt.Errorf("expected Float to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPolygon(v *[]types.Point, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Point + if *v == nil { + cv = []types.Point{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Point + destAddr := &col + if err := awsAwsjson11_deserializeDocumentPoint(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentPrediction(v **types.Prediction, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Prediction + if *v == nil { + sv = &types.Prediction{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "Value": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NonEmptyString to be of type string, got %T instead", value) + } + sv.Value = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPredictionList(v *[]types.Prediction, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Prediction + if *v == nil { + cv = []types.Prediction{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Prediction + destAddr := &col + if err := awsAwsjson11_deserializeDocumentPrediction(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentProvisionedThroughputExceededException(v **types.ProvisionedThroughputExceededException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ProvisionedThroughputExceededException + if *v == nil { + sv = &types.ProvisionedThroughputExceededException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentQuery(v **types.Query, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Query + if *v == nil { + sv = &types.Query{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Alias": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected QueryInput to be of type string, got %T instead", value) + } + sv.Alias = ptr.String(jtv) + } + + case "Pages": + if err := awsAwsjson11_deserializeDocumentQueryPages(&sv.Pages, value); err != nil { + return err + } + + case "Text": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected QueryInput to be of type string, got %T instead", value) + } + sv.Text = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentQueryPages(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected QueryPage to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentRelationship(v **types.Relationship, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Relationship + if *v == nil { + sv = &types.Relationship{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Ids": + if err := awsAwsjson11_deserializeDocumentIdList(&sv.Ids, value); err != nil { + return err + } + + case "Type": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RelationshipType to be of type string, got %T instead", value) + } + sv.Type = types.RelationshipType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRelationshipList(v *[]types.Relationship, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Relationship + if *v == nil { + cv = []types.Relationship{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Relationship + destAddr := &col + if err := awsAwsjson11_deserializeDocumentRelationship(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ResourceNotFoundException + if *v == nil { + sv = &types.ResourceNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentS3Object(v **types.S3Object, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.S3Object + if *v == nil { + sv = &types.S3Object{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Bucket": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3Bucket to be of type string, got %T instead", value) + } + sv.Bucket = ptr.String(jtv) + } + + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3ObjectName to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "Version": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3ObjectVersion to be of type string, got %T instead", value) + } + sv.Version = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentServiceQuotaExceededException(v **types.ServiceQuotaExceededException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ServiceQuotaExceededException + if *v == nil { + sv = &types.ServiceQuotaExceededException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSignatureDetection(v **types.SignatureDetection, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SignatureDetection + if *v == nil { + sv = &types.SignatureDetection{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Confidence": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.Confidence = ptr.Float32(float32(f64)) + + case string: + var f64 float64 + switch { + case strings.EqualFold(jtv, "NaN"): + f64 = math.NaN() + + case strings.EqualFold(jtv, "Infinity"): + f64 = math.Inf(1) + + case strings.EqualFold(jtv, "-Infinity"): + f64 = math.Inf(-1) + + default: + return fmt.Errorf("unknown JSON number value: %s", jtv) + + } + sv.Confidence = ptr.Float32(float32(f64)) + + default: + return fmt.Errorf("expected Percent to be a JSON Number, got %T instead", value) + + } + } + + case "Geometry": + if err := awsAwsjson11_deserializeDocumentGeometry(&sv.Geometry, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSignatureDetectionList(v *[]types.SignatureDetection, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.SignatureDetection + if *v == nil { + cv = []types.SignatureDetection{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.SignatureDetection + destAddr := &col + if err := awsAwsjson11_deserializeDocumentSignatureDetection(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentSplitDocument(v **types.SplitDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SplitDocument + if *v == nil { + sv = &types.SplitDocument{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Index": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Index = ptr.Int32(int32(i64)) + } + + case "Pages": + if err := awsAwsjson11_deserializeDocumentPageList(&sv.Pages, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSplitDocumentList(v *[]types.SplitDocument, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.SplitDocument + if *v == nil { + cv = []types.SplitDocument{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.SplitDocument + destAddr := &col + if err := awsAwsjson11_deserializeDocumentSplitDocument(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentStringList(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentTagMap(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TagValue to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentThrottlingException(v **types.ThrottlingException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ThrottlingException + if *v == nil { + sv = &types.ThrottlingException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUndetectedDocumentTypeList(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NonEmptyString to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUndetectedSignature(v **types.UndetectedSignature, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UndetectedSignature + if *v == nil { + sv = &types.UndetectedSignature{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Page": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected UInteger to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Page = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUndetectedSignatureList(v *[]types.UndetectedSignature, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UndetectedSignature + if *v == nil { + cv = []types.UndetectedSignature{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UndetectedSignature + destAddr := &col + if err := awsAwsjson11_deserializeDocumentUndetectedSignature(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUnsupportedDocumentException(v **types.UnsupportedDocumentException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnsupportedDocumentException + if *v == nil { + sv = &types.UnsupportedDocumentException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentValidationException(v **types.ValidationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ValidationException + if *v == nil { + sv = &types.ValidationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Code": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Code = ptr.String(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWarning(v **types.Warning, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.Warning + if *v == nil { + sv = &types.Warning{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ErrorCode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ErrorCode to be of type string, got %T instead", value) + } + sv.ErrorCode = ptr.String(jtv) + } + + case "Pages": + if err := awsAwsjson11_deserializeDocumentPages(&sv.Pages, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWarnings(v *[]types.Warning, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.Warning + if *v == nil { + cv = []types.Warning{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Warning + destAddr := &col + if err := awsAwsjson11_deserializeDocumentWarning(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAnalyzeDocumentOutput(v **AnalyzeDocumentOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AnalyzeDocumentOutput + if *v == nil { + sv = &AnalyzeDocumentOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeDocumentModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeDocumentModelVersion = ptr.String(jtv) + } + + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "HumanLoopActivationOutput": + if err := awsAwsjson11_deserializeDocumentHumanLoopActivationOutput(&sv.HumanLoopActivationOutput, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAnalyzeExpenseOutput(v **AnalyzeExpenseOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AnalyzeExpenseOutput + if *v == nil { + sv = &AnalyzeExpenseOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "ExpenseDocuments": + if err := awsAwsjson11_deserializeDocumentExpenseDocumentList(&sv.ExpenseDocuments, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAnalyzeIDOutput(v **AnalyzeIDOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AnalyzeIDOutput + if *v == nil { + sv = &AnalyzeIDOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeIDModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeIDModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "IdentityDocuments": + if err := awsAwsjson11_deserializeDocumentIdentityDocumentList(&sv.IdentityDocuments, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateAdapterOutput(v **CreateAdapterOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateAdapterOutput + if *v == nil { + sv = &CreateAdapterOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateAdapterVersionOutput(v **CreateAdapterVersionOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateAdapterVersionOutput + if *v == nil { + sv = &CreateAdapterVersionOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersion to be of type string, got %T instead", value) + } + sv.AdapterVersion = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDeleteAdapterOutput(v **DeleteAdapterOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteAdapterOutput + if *v == nil { + sv = &DeleteAdapterOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDeleteAdapterVersionOutput(v **DeleteAdapterVersionOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteAdapterVersionOutput + if *v == nil { + sv = &DeleteAdapterVersionOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDetectDocumentTextOutput(v **DetectDocumentTextOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DetectDocumentTextOutput + if *v == nil { + sv = &DetectDocumentTextOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "DetectDocumentTextModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.DetectDocumentTextModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetAdapterOutput(v **GetAdapterOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetAdapterOutput + if *v == nil { + sv = &GetAdapterOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterName to be of type string, got %T instead", value) + } + sv.AdapterName = ptr.String(jtv) + } + + case "AutoUpdate": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AutoUpdate to be of type string, got %T instead", value) + } + sv.AutoUpdate = types.AutoUpdate(jtv) + } + + case "CreationTime": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) + + } + } + + case "Description": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterDescription to be of type string, got %T instead", value) + } + sv.Description = ptr.String(jtv) + } + + case "FeatureTypes": + if err := awsAwsjson11_deserializeDocumentFeatureTypes(&sv.FeatureTypes, value); err != nil { + return err + } + + case "Tags": + if err := awsAwsjson11_deserializeDocumentTagMap(&sv.Tags, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetAdapterVersionOutput(v **GetAdapterVersionOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetAdapterVersionOutput + if *v == nil { + sv = &GetAdapterVersionOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersion to be of type string, got %T instead", value) + } + sv.AdapterVersion = ptr.String(jtv) + } + + case "CreationTime": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) + + } + } + + case "DatasetConfig": + if err := awsAwsjson11_deserializeDocumentAdapterVersionDatasetConfig(&sv.DatasetConfig, value); err != nil { + return err + } + + case "EvaluationMetrics": + if err := awsAwsjson11_deserializeDocumentAdapterVersionEvaluationMetrics(&sv.EvaluationMetrics, value); err != nil { + return err + } + + case "FeatureTypes": + if err := awsAwsjson11_deserializeDocumentFeatureTypes(&sv.FeatureTypes, value); err != nil { + return err + } + + case "KMSKeyId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected KMSKeyId to be of type string, got %T instead", value) + } + sv.KMSKeyId = ptr.String(jtv) + } + + case "OutputConfig": + if err := awsAwsjson11_deserializeDocumentOutputConfig(&sv.OutputConfig, value); err != nil { + return err + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersionStatus to be of type string, got %T instead", value) + } + sv.Status = types.AdapterVersionStatus(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterVersionStatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Tags": + if err := awsAwsjson11_deserializeDocumentTagMap(&sv.Tags, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetDocumentAnalysisOutput(v **GetDocumentAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetDocumentAnalysisOutput + if *v == nil { + sv = &GetDocumentAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeDocumentModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeDocumentModelVersion = ptr.String(jtv) + } + + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "JobStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) + } + sv.JobStatus = types.JobStatus(jtv) + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Warnings": + if err := awsAwsjson11_deserializeDocumentWarnings(&sv.Warnings, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetDocumentTextDetectionOutput(v **GetDocumentTextDetectionOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetDocumentTextDetectionOutput + if *v == nil { + sv = &GetDocumentTextDetectionOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Blocks": + if err := awsAwsjson11_deserializeDocumentBlockList(&sv.Blocks, value); err != nil { + return err + } + + case "DetectDocumentTextModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.DetectDocumentTextModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "JobStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) + } + sv.JobStatus = types.JobStatus(jtv) + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Warnings": + if err := awsAwsjson11_deserializeDocumentWarnings(&sv.Warnings, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetExpenseAnalysisOutput(v **GetExpenseAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetExpenseAnalysisOutput + if *v == nil { + sv = &GetExpenseAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeExpenseModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeExpenseModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "ExpenseDocuments": + if err := awsAwsjson11_deserializeDocumentExpenseDocumentList(&sv.ExpenseDocuments, value); err != nil { + return err + } + + case "JobStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) + } + sv.JobStatus = types.JobStatus(jtv) + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Warnings": + if err := awsAwsjson11_deserializeDocumentWarnings(&sv.Warnings, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetLendingAnalysisOutput(v **GetLendingAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetLendingAnalysisOutput + if *v == nil { + sv = &GetLendingAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeLendingModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeLendingModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "JobStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) + } + sv.JobStatus = types.JobStatus(jtv) + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "Results": + if err := awsAwsjson11_deserializeDocumentLendingResultList(&sv.Results, value); err != nil { + return err + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Warnings": + if err := awsAwsjson11_deserializeDocumentWarnings(&sv.Warnings, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetLendingAnalysisSummaryOutput(v **GetLendingAnalysisSummaryOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetLendingAnalysisSummaryOutput + if *v == nil { + sv = &GetLendingAnalysisSummaryOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AnalyzeLendingModelVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AnalyzeLendingModelVersion = ptr.String(jtv) + } + + case "DocumentMetadata": + if err := awsAwsjson11_deserializeDocumentDocumentMetadata(&sv.DocumentMetadata, value); err != nil { + return err + } + + case "JobStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) + } + sv.JobStatus = types.JobStatus(jtv) + } + + case "StatusMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) + } + sv.StatusMessage = ptr.String(jtv) + } + + case "Summary": + if err := awsAwsjson11_deserializeDocumentLendingSummary(&sv.Summary, value); err != nil { + return err + } + + case "Warnings": + if err := awsAwsjson11_deserializeDocumentWarnings(&sv.Warnings, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListAdaptersOutput(v **ListAdaptersOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListAdaptersOutput + if *v == nil { + sv = &ListAdaptersOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Adapters": + if err := awsAwsjson11_deserializeDocumentAdapterList(&sv.Adapters, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListAdapterVersionsOutput(v **ListAdapterVersionsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListAdapterVersionsOutput + if *v == nil { + sv = &ListAdapterVersionsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterVersions": + if err := awsAwsjson11_deserializeDocumentAdapterVersionList(&sv.AdapterVersions, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsForResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListTagsForResourceOutput + if *v == nil { + sv = &ListTagsForResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Tags": + if err := awsAwsjson11_deserializeDocumentTagMap(&sv.Tags, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartDocumentAnalysisOutput(v **StartDocumentAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartDocumentAnalysisOutput + if *v == nil { + sv = &StartDocumentAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "JobId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobId to be of type string, got %T instead", value) + } + sv.JobId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartDocumentTextDetectionOutput(v **StartDocumentTextDetectionOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartDocumentTextDetectionOutput + if *v == nil { + sv = &StartDocumentTextDetectionOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "JobId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobId to be of type string, got %T instead", value) + } + sv.JobId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartExpenseAnalysisOutput(v **StartExpenseAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartExpenseAnalysisOutput + if *v == nil { + sv = &StartExpenseAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "JobId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobId to be of type string, got %T instead", value) + } + sv.JobId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartLendingAnalysisOutput(v **StartLendingAnalysisOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartLendingAnalysisOutput + if *v == nil { + sv = &StartLendingAnalysisOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "JobId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected JobId to be of type string, got %T instead", value) + } + sv.JobId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentTagResourceOutput(v **TagResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *TagResourceOutput + if *v == nil { + sv = &TagResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUntagResourceOutput(v **UntagResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UntagResourceOutput + if *v == nil { + sv = &UntagResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateAdapterOutput(v **UpdateAdapterOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateAdapterOutput + if *v == nil { + sv = &UpdateAdapterOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdapterId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterId to be of type string, got %T instead", value) + } + sv.AdapterId = ptr.String(jtv) + } + + case "AdapterName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterName to be of type string, got %T instead", value) + } + sv.AdapterName = ptr.String(jtv) + } + + case "AutoUpdate": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AutoUpdate to be of type string, got %T instead", value) + } + sv.AutoUpdate = types.AutoUpdate(jtv) + } + + case "CreationTime": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) + + } + } + + case "Description": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdapterDescription to be of type string, got %T instead", value) + } + sv.Description = ptr.String(jtv) + } + + case "FeatureTypes": + if err := awsAwsjson11_deserializeDocumentFeatureTypes(&sv.FeatureTypes, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +type protocolErrorInfo struct { + Type string `json:"__type"` + Message string + Code any // nonstandard for awsjson but some services do present the type here +} + +func getProtocolErrorInfo(decoder *json.Decoder) (protocolErrorInfo, error) { + var errInfo protocolErrorInfo + if err := decoder.Decode(&errInfo); err != nil { + if err == io.EOF { + return errInfo, nil + } + return errInfo, err + } + + return errInfo, nil +} + +func resolveProtocolErrorType(headerType string, bodyInfo protocolErrorInfo) (string, bool) { + if len(headerType) != 0 { + return headerType, true + } else if len(bodyInfo.Type) != 0 { + return bodyInfo.Type, true + } else if code, ok := bodyInfo.Code.(string); ok && len(code) != 0 { + return code, true + } + return "", false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/doc.go new file mode 100644 index 00000000..c550456f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/doc.go @@ -0,0 +1,9 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +// Package textract provides the API client, operations, and parameter types for +// Amazon Textract. +// +// Amazon Textract detects and analyzes text in documents and converts it into +// machine-readable text. This is the API reference documentation for Amazon +// Textract. +package textract diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/endpoints.go new file mode 100644 index 00000000..024c2952 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/endpoints.go @@ -0,0 +1,537 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + "github.com/aws/aws-sdk-go-v2/internal/endpoints" + "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" + internalendpoints "github.com/aws/aws-sdk-go-v2/service/textract/internal/endpoints" + smithyauth "github.com/aws/smithy-go/auth" + smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" + "net/url" + "os" + "strings" +) + +// EndpointResolverOptions is the service endpoint resolver options +type EndpointResolverOptions = internalendpoints.Options + +// EndpointResolver interface for resolving service endpoints. +type EndpointResolver interface { + ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) +} + +var _ EndpointResolver = &internalendpoints.Resolver{} + +// NewDefaultEndpointResolver constructs a new service endpoint resolver +func NewDefaultEndpointResolver() *internalendpoints.Resolver { + return internalendpoints.New() +} + +// EndpointResolverFunc is a helper utility that wraps a function so it satisfies +// the EndpointResolver interface. This is useful when you want to add additional +// endpoint resolving logic, or stub out specific endpoints with custom values. +type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) + +func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return fn(region, options) +} + +// EndpointResolverFromURL returns an EndpointResolver configured using the +// provided endpoint url. By default, the resolved endpoint resolver uses the +// client region as signing region, and the endpoint source is set to +// EndpointSourceCustom.You can provide functional options to configure endpoint +// values for the resolved endpoint. +func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { + e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} + for _, fn := range optFns { + fn(&e) + } + + return EndpointResolverFunc( + func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { + if len(e.SigningRegion) == 0 { + e.SigningRegion = region + } + return e, nil + }, + ) +} + +type ResolveEndpoint struct { + Resolver EndpointResolver + Options EndpointResolverOptions +} + +func (*ResolveEndpoint) ID() string { + return "ResolveEndpoint" +} + +func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleSerialize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.Resolver == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + eo := m.Options + eo.Logger = middleware.GetLogger(ctx) + + var endpoint aws.Endpoint + endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) + if err != nil { + nf := (&aws.EndpointNotFoundError{}) + if errors.As(err, &nf) { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) + return next.HandleSerialize(ctx, in) + } + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + req.URL, err = url.Parse(endpoint.URL) + if err != nil { + return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) + } + + if len(awsmiddleware.GetSigningName(ctx)) == 0 { + signingName := endpoint.SigningName + if len(signingName) == 0 { + signingName = "textract" + } + ctx = awsmiddleware.SetSigningName(ctx, signingName) + } + ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) + ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) + ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) + ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) + return next.HandleSerialize(ctx, in) +} +func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { + return stack.Serialize.Insert(&ResolveEndpoint{ + Resolver: o.EndpointResolver, + Options: o.EndpointOptions, + }, "OperationSerializer", middleware.Before) +} + +func removeResolveEndpointMiddleware(stack *middleware.Stack) error { + _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) + return err +} + +type wrappedEndpointResolver struct { + awsResolver aws.EndpointResolverWithOptions +} + +func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return w.awsResolver.ResolveEndpoint(ServiceID, region, options) +} + +type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) + +func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { + return a(service, region) +} + +var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) + +// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. +// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, +// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked +// via its middleware. +// +// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. +func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { + var resolver aws.EndpointResolverWithOptions + + if awsResolverWithOptions != nil { + resolver = awsResolverWithOptions + } else if awsResolver != nil { + resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) + } + + return &wrappedEndpointResolver{ + awsResolver: resolver, + } +} + +func finalizeClientEndpointResolverOptions(options *Options) { + options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() + + if len(options.EndpointOptions.ResolvedRegion) == 0 { + const fipsInfix = "-fips-" + const fipsPrefix = "fips-" + const fipsSuffix = "-fips" + + if strings.Contains(options.Region, fipsInfix) || + strings.Contains(options.Region, fipsPrefix) || + strings.Contains(options.Region, fipsSuffix) { + options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( + options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") + options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled + } + } + +} + +func resolveEndpointResolverV2(options *Options) { + if options.EndpointResolverV2 == nil { + options.EndpointResolverV2 = NewDefaultEndpointResolverV2() + } +} + +func resolveBaseEndpoint(cfg aws.Config, o *Options) { + if cfg.BaseEndpoint != nil { + o.BaseEndpoint = cfg.BaseEndpoint + } + + _, g := os.LookupEnv("AWS_ENDPOINT_URL") + _, s := os.LookupEnv("AWS_ENDPOINT_URL_TEXTRACT") + + if g && !s { + return + } + + value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "Textract", cfg.ConfigSources) + if found && err == nil { + o.BaseEndpoint = &value + } +} + +func bindRegion(region string) *string { + if region == "" { + return nil + } + return aws.String(endpoints.MapFIPSRegion(region)) +} + +// EndpointParameters provides the parameters that influence how endpoints are +// resolved. +type EndpointParameters struct { + // The AWS region used to dispatch the request. + // + // Parameter is + // required. + // + // AWS::Region + Region *string + + // When true, use the dual-stack endpoint. If the configured endpoint does not + // support dual-stack, dispatching the request MAY return an error. + // + // Defaults to + // false if no value is provided. + // + // AWS::UseDualStack + UseDualStack *bool + + // When true, send this request to the FIPS-compliant regional endpoint. If the + // configured endpoint does not have a FIPS compliant endpoint, dispatching the + // request will return an error. + // + // Defaults to false if no value is + // provided. + // + // AWS::UseFIPS + UseFIPS *bool + + // Override the endpoint used to send this request + // + // Parameter is + // required. + // + // SDK::Endpoint + Endpoint *string +} + +// ValidateRequired validates required parameters are set. +func (p EndpointParameters) ValidateRequired() error { + if p.UseDualStack == nil { + return fmt.Errorf("parameter UseDualStack is required") + } + + if p.UseFIPS == nil { + return fmt.Errorf("parameter UseFIPS is required") + } + + return nil +} + +// WithDefaults returns a shallow copy of EndpointParameterswith default values +// applied to members where applicable. +func (p EndpointParameters) WithDefaults() EndpointParameters { + if p.UseDualStack == nil { + p.UseDualStack = ptr.Bool(false) + } + + if p.UseFIPS == nil { + p.UseFIPS = ptr.Bool(false) + } + return p +} + +type stringSlice []string + +func (s stringSlice) Get(i int) *string { + if i < 0 || i >= len(s) { + return nil + } + + v := s[i] + return &v +} + +// EndpointResolverV2 provides the interface for resolving service endpoints. +type EndpointResolverV2 interface { + // ResolveEndpoint attempts to resolve the endpoint with the provided options, + // returning the endpoint if found. Otherwise an error is returned. + ResolveEndpoint(ctx context.Context, params EndpointParameters) ( + smithyendpoints.Endpoint, error, + ) +} + +// resolver provides the implementation for resolving endpoints. +type resolver struct{} + +func NewDefaultEndpointResolverV2() EndpointResolverV2 { + return &resolver{} +} + +// ResolveEndpoint attempts to resolve the endpoint with the provided options, +// returning the endpoint if found. Otherwise an error is returned. +func (r *resolver) ResolveEndpoint( + ctx context.Context, params EndpointParameters, +) ( + endpoint smithyendpoints.Endpoint, err error, +) { + params = params.WithDefaults() + if err = params.ValidateRequired(); err != nil { + return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) + } + _UseDualStack := *params.UseDualStack + _UseFIPS := *params.UseFIPS + + if exprVal := params.Endpoint; exprVal != nil { + _Endpoint := *exprVal + _ = _Endpoint + if _UseFIPS == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") + } + if _UseDualStack == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") + } + uriString := _Endpoint + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if exprVal := params.Region; exprVal != nil { + _Region := *exprVal + _ = _Region + if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { + _PartitionResult := *exprVal + _ = _PartitionResult + if _UseFIPS == true { + if _UseDualStack == true { + if true == _PartitionResult.SupportsFIPS { + if true == _PartitionResult.SupportsDualStack { + uriString := func() string { + var out strings.Builder + out.WriteString("https://textract-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") + } + } + if _UseFIPS == true { + if true == _PartitionResult.SupportsFIPS { + uriString := func() string { + var out strings.Builder + out.WriteString("https://textract-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") + } + if _UseDualStack == true { + if true == _PartitionResult.SupportsDualStack { + uriString := func() string { + var out strings.Builder + out.WriteString("https://textract.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") + } + uriString := func() string { + var out strings.Builder + out.WriteString("https://textract.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") +} + +type endpointParamsBinder interface { + bindEndpointParams(*EndpointParameters) +} + +func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { + params := &EndpointParameters{} + + params.Region = bindRegion(options.Region) + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) + params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) + params.Endpoint = options.BaseEndpoint + + if b, ok := input.(endpointParamsBinder); ok { + b.bindEndpointParams(params) + } + + return params +} + +type resolveEndpointV2Middleware struct { + options Options +} + +func (*resolveEndpointV2Middleware) ID() string { + return "ResolveEndpointV2" +} + +func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveEndpoint") + defer span.End() + + if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleFinalize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.options.EndpointResolverV2 == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", + func() (smithyendpoints.Endpoint, error) { + return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) + }) + if err != nil { + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + span.SetProperty("client.call.resolved_endpoint", endpt.URI.String()) + + if endpt.URI.RawPath == "" && req.URL.RawPath != "" { + endpt.URI.RawPath = endpt.URI.Path + } + req.URL.Scheme = endpt.URI.Scheme + req.URL.Host = endpt.URI.Host + req.URL.Path = smithyhttp.JoinPath(endpt.URI.Path, req.URL.Path) + req.URL.RawPath = smithyhttp.JoinPath(endpt.URI.RawPath, req.URL.RawPath) + for k := range endpt.Headers { + req.Header.Set(k, endpt.Headers.Get(k)) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + opts, _ := smithyauth.GetAuthOptions(&endpt.Properties) + for _, o := range opts { + rscheme.SignerProperties.SetAll(&o.SignerProperties) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/generated.json new file mode 100644 index 00000000..71a7a082 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/generated.json @@ -0,0 +1,58 @@ +{ + "dependencies": { + "github.com/aws/aws-sdk-go-v2": "v1.4.0", + "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", + "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", + "github.com/aws/smithy-go": "v1.4.0" + }, + "files": [ + "api_client.go", + "api_client_test.go", + "api_op_AnalyzeDocument.go", + "api_op_AnalyzeExpense.go", + "api_op_AnalyzeID.go", + "api_op_CreateAdapter.go", + "api_op_CreateAdapterVersion.go", + "api_op_DeleteAdapter.go", + "api_op_DeleteAdapterVersion.go", + "api_op_DetectDocumentText.go", + "api_op_GetAdapter.go", + "api_op_GetAdapterVersion.go", + "api_op_GetDocumentAnalysis.go", + "api_op_GetDocumentTextDetection.go", + "api_op_GetExpenseAnalysis.go", + "api_op_GetLendingAnalysis.go", + "api_op_GetLendingAnalysisSummary.go", + "api_op_ListAdapterVersions.go", + "api_op_ListAdapters.go", + "api_op_ListTagsForResource.go", + "api_op_StartDocumentAnalysis.go", + "api_op_StartDocumentTextDetection.go", + "api_op_StartExpenseAnalysis.go", + "api_op_StartLendingAnalysis.go", + "api_op_TagResource.go", + "api_op_UntagResource.go", + "api_op_UpdateAdapter.go", + "auth.go", + "deserializers.go", + "doc.go", + "endpoints.go", + "endpoints_config_test.go", + "endpoints_test.go", + "generated.json", + "internal/endpoints/endpoints.go", + "internal/endpoints/endpoints_test.go", + "options.go", + "protocol_test.go", + "serializers.go", + "snapshot_test.go", + "sra_operation_order_test.go", + "types/enums.go", + "types/errors.go", + "types/types.go", + "validators.go" + ], + "go": "1.22", + "module": "github.com/aws/aws-sdk-go-v2/service/textract", + "unstable": false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/go_module_metadata.go new file mode 100644 index 00000000..2d3d2ebf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/go_module_metadata.go @@ -0,0 +1,6 @@ +// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. + +package textract + +// goModuleVersion is the tagged release for this module +const goModuleVersion = "1.35.1" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/internal/endpoints/endpoints.go new file mode 100644 index 00000000..e2526571 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/internal/endpoints/endpoints.go @@ -0,0 +1,604 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package endpoints + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" + "github.com/aws/smithy-go/logging" + "regexp" +) + +// Options is the endpoint resolver configuration options +type Options struct { + // Logger is a logging implementation that log events should be sent to. + Logger logging.Logger + + // LogDeprecated indicates that deprecated endpoints should be logged to the + // provided logger. + LogDeprecated bool + + // ResolvedRegion is used to override the region to be resolved, rather then the + // using the value passed to the ResolveEndpoint method. This value is used by the + // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative + // name. You must not set this value directly in your application. + ResolvedRegion string + + // DisableHTTPS informs the resolver to return an endpoint that does not use the + // HTTPS scheme. + DisableHTTPS bool + + // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. + UseDualStackEndpoint aws.DualStackEndpointState + + // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. + UseFIPSEndpoint aws.FIPSEndpointState +} + +func (o Options) GetResolvedRegion() string { + return o.ResolvedRegion +} + +func (o Options) GetDisableHTTPS() bool { + return o.DisableHTTPS +} + +func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { + return o.UseDualStackEndpoint +} + +func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { + return o.UseFIPSEndpoint +} + +func transformToSharedOptions(options Options) endpoints.Options { + return endpoints.Options{ + Logger: options.Logger, + LogDeprecated: options.LogDeprecated, + ResolvedRegion: options.ResolvedRegion, + DisableHTTPS: options.DisableHTTPS, + UseDualStackEndpoint: options.UseDualStackEndpoint, + UseFIPSEndpoint: options.UseFIPSEndpoint, + } +} + +// Resolver Textract endpoint resolver +type Resolver struct { + partitions endpoints.Partitions +} + +// ResolveEndpoint resolves the service endpoint for the given region and options +func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { + if len(region) == 0 { + return endpoint, &aws.MissingRegionError{} + } + + opt := transformToSharedOptions(options) + return r.partitions.ResolveEndpoint(region, opt) +} + +// New returns a new Resolver +func New() *Resolver { + return &Resolver{ + partitions: defaultPartitions, + } +} + +var partitionRegexp = struct { + Aws *regexp.Regexp + AwsCn *regexp.Regexp + AwsIso *regexp.Regexp + AwsIsoB *regexp.Regexp + AwsIsoE *regexp.Regexp + AwsIsoF *regexp.Regexp + AwsUsGov *regexp.Regexp +}{ + + Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$"), + AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), + AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), + AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), + AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), + AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), + AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), +} + +var defaultPartitions = endpoints.Partitions{ + { + ID: "aws", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.Aws, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "ap-northeast-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-northeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.ap-northeast-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "ap-south-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.ap-south-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.ap-southeast-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.ap-southeast-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "ca-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ca-central-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.ca-central-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ca-central-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.ca-central-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "ca-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.ca-central-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "eu-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.eu-central-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "eu-south-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-south-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.eu-south-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "eu-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.eu-west-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "eu-west-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.eu-west-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "eu-west-3", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.eu-west-3.api.aws", + }, + endpoints.EndpointKey{ + Region: "fips-ca-central-1", + }: endpoints.Endpoint{ + Hostname: "textract-fips.ca-central-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "ca-central-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-east-1", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-east-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-east-2", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-east-2.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-2", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-west-1", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-west-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-west-2", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-west-2.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-2", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "us-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-east-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-east-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-east-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-east-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-east-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-west-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-west-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-west-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-west-2.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-west-2.api.aws", + }, + }, + }, + { + ID: "aws-cn", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsCn, + IsRegionalized: true, + }, + { + ID: "aws-iso", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIso, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "us-iso-east-1", + }: endpoints.Endpoint{}, + }, + }, + { + ID: "aws-iso-b", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoB, + IsRegionalized: true, + }, + { + ID: "aws-iso-e", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoE, + IsRegionalized: true, + }, + { + ID: "aws-iso-f", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoF, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "us-isof-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-isof-south-1", + }: endpoints.Endpoint{}, + }, + }, + { + ID: "aws-us-gov", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "textract.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsUsGov, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "fips-us-gov-east-1", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-gov-east-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-gov-west-1", + }: endpoints.Endpoint{ + Hostname: "textract-fips.us-gov-west-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-gov-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-gov-east-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-gov-east-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "textract-fips.us-gov-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "textract-fips.us-gov-west-1.api.aws", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "textract.us-gov-west-1.api.aws", + }, + }, + }, +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/options.go new file mode 100644 index 00000000..4eacab04 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/options.go @@ -0,0 +1,236 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" +) + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} + +type Options struct { + // Set of options to modify how an operation is invoked. These apply to all + // operations invoked for this client. Use functional options on operation call to + // modify this list for per operation behavior. + APIOptions []func(*middleware.Stack) error + + // The optional application specific identifier appended to the User-Agent header. + AppID string + + // This endpoint will be given as input to an EndpointResolverV2. It is used for + // providing a custom base endpoint that is subject to modifications by the + // processing EndpointResolverV2. + BaseEndpoint *string + + // Configures the events that will be sent to the configured logger. + ClientLogMode aws.ClientLogMode + + // The credentials object to use when signing requests. + Credentials aws.CredentialsProvider + + // The configuration DefaultsMode that the SDK should use when constructing the + // clients initial default settings. + DefaultsMode aws.DefaultsMode + + // The endpoint options to be used when attempting to resolve an endpoint. + EndpointOptions EndpointResolverOptions + + // The service endpoint resolver. + // + // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a + // value for this field will likely prevent you from using any endpoint-related + // service features released after the introduction of EndpointResolverV2 and + // BaseEndpoint. + // + // To migrate an EndpointResolver implementation that uses a custom endpoint, set + // the client option BaseEndpoint instead. + EndpointResolver EndpointResolver + + // Resolves the endpoint used for a particular service operation. This should be + // used over the deprecated EndpointResolver. + EndpointResolverV2 EndpointResolverV2 + + // Signature Version 4 (SigV4) Signer + HTTPSignerV4 HTTPSignerV4 + + // Provides idempotency tokens values that will be automatically populated into + // idempotent API operations. + IdempotencyTokenProvider IdempotencyTokenProvider + + // The logger writer interface to write logging messages to. + Logger logging.Logger + + // The client meter provider. + MeterProvider metrics.MeterProvider + + // The region to send requests to. (Required) + Region string + + // RetryMaxAttempts specifies the maximum number attempts an API client will call + // an operation that fails with a retryable error. A value of 0 is ignored, and + // will not be used to configure the API client created default retryer, or modify + // per operation call's retry max attempts. + // + // If specified in an operation call's functional options with a value that is + // different than the constructed client's Options, the Client's Retryer will be + // wrapped to use the operation's specific RetryMaxAttempts value. + RetryMaxAttempts int + + // RetryMode specifies the retry mode the API client will be created with, if + // Retryer option is not also specified. + // + // When creating a new API Clients this member will only be used if the Retryer + // Options member is nil. This value will be ignored if Retryer is not nil. + // + // Currently does not support per operation call overrides, may in the future. + RetryMode aws.RetryMode + + // Retryer guides how HTTP requests should be retried in case of recoverable + // failures. When nil the API client will use a default retryer. The kind of + // default retry created by the API client can be changed with the RetryMode + // option. + Retryer aws.Retryer + + // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set + // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You + // should not populate this structure programmatically, or rely on the values here + // within your applications. + RuntimeEnvironment aws.RuntimeEnvironment + + // The client tracer provider. + TracerProvider tracing.TracerProvider + + // The initial DefaultsMode used when the client options were constructed. If the + // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved + // value was at that point in time. + // + // Currently does not support per operation call overrides, may in the future. + resolvedDefaultsMode aws.DefaultsMode + + // The HTTP client to invoke API calls with. Defaults to client's default HTTP + // implementation if nil. + HTTPClient HTTPClient + + // The auth scheme resolver which determines how to authenticate for each + // operation. + AuthSchemeResolver AuthSchemeResolver + + // The list of auth schemes supported by the client. + AuthSchemes []smithyhttp.AuthScheme +} + +// Copy creates a clone where the APIOptions list is deep copied. +func (o Options) Copy() Options { + to := o + to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) + copy(to.APIOptions, o.APIOptions) + + return to +} + +func (o Options) GetIdentityResolver(schemeID string) smithyauth.IdentityResolver { + if schemeID == "aws.auth#sigv4" { + return getSigV4IdentityResolver(o) + } + if schemeID == "smithy.api#noAuth" { + return &smithyauth.AnonymousIdentityResolver{} + } + return nil +} + +// WithAPIOptions returns a functional option for setting the Client's APIOptions +// option. +func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { + return func(o *Options) { + o.APIOptions = append(o.APIOptions, optFns...) + } +} + +// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for +// this field will likely prevent you from using any endpoint-related service +// features released after the introduction of EndpointResolverV2 and BaseEndpoint. +// +// To migrate an EndpointResolver implementation that uses a custom endpoint, set +// the client option BaseEndpoint instead. +func WithEndpointResolver(v EndpointResolver) func(*Options) { + return func(o *Options) { + o.EndpointResolver = v + } +} + +// WithEndpointResolverV2 returns a functional option for setting the Client's +// EndpointResolverV2 option. +func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { + return func(o *Options) { + o.EndpointResolverV2 = v + } +} + +func getSigV4IdentityResolver(o Options) smithyauth.IdentityResolver { + if o.Credentials != nil { + return &internalauthsmithy.CredentialsProviderAdapter{Provider: o.Credentials} + } + return nil +} + +// WithSigV4SigningName applies an override to the authentication workflow to +// use the given signing name for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing name from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningName(name string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningName(ctx, name), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningName", fn), + middleware.Before, + ) + }) + } +} + +// WithSigV4SigningRegion applies an override to the authentication workflow to +// use the given signing region for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing region from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningRegion(region string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), + middleware.Before, + ) + }) + } +} + +func ignoreAnonymousAuth(options *Options) { + if aws.IsCredentialsProvider(options.Credentials, (*aws.AnonymousCredentials)(nil)) { + options.Credentials = nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/serializers.go new file mode 100644 index 00000000..6f416d89 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/serializers.go @@ -0,0 +1,2519 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "bytes" + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/encoding/httpbinding" + smithyjson "github.com/aws/smithy-go/encoding/json" + "github.com/aws/smithy-go/middleware" + smithytime "github.com/aws/smithy-go/time" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "path" +) + +type awsAwsjson11_serializeOpAnalyzeDocument struct { +} + +func (*awsAwsjson11_serializeOpAnalyzeDocument) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAnalyzeDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AnalyzeDocumentInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.AnalyzeDocument") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAnalyzeDocumentInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAnalyzeExpense struct { +} + +func (*awsAwsjson11_serializeOpAnalyzeExpense) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAnalyzeExpense) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AnalyzeExpenseInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.AnalyzeExpense") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAnalyzeExpenseInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAnalyzeID struct { +} + +func (*awsAwsjson11_serializeOpAnalyzeID) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAnalyzeID) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AnalyzeIDInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.AnalyzeID") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAnalyzeIDInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateAdapter struct { +} + +func (*awsAwsjson11_serializeOpCreateAdapter) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateAdapter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateAdapterInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.CreateAdapter") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateAdapterInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateAdapterVersion struct { +} + +func (*awsAwsjson11_serializeOpCreateAdapterVersion) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateAdapterVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateAdapterVersionInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.CreateAdapterVersion") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateAdapterVersionInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteAdapter struct { +} + +func (*awsAwsjson11_serializeOpDeleteAdapter) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteAdapter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteAdapterInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.DeleteAdapter") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteAdapterInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteAdapterVersion struct { +} + +func (*awsAwsjson11_serializeOpDeleteAdapterVersion) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteAdapterVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteAdapterVersionInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.DeleteAdapterVersion") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteAdapterVersionInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDetectDocumentText struct { +} + +func (*awsAwsjson11_serializeOpDetectDocumentText) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDetectDocumentText) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DetectDocumentTextInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.DetectDocumentText") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDetectDocumentTextInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetAdapter struct { +} + +func (*awsAwsjson11_serializeOpGetAdapter) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetAdapter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetAdapterInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetAdapter") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetAdapterInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetAdapterVersion struct { +} + +func (*awsAwsjson11_serializeOpGetAdapterVersion) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetAdapterVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetAdapterVersionInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetAdapterVersion") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetAdapterVersionInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetDocumentAnalysis struct { +} + +func (*awsAwsjson11_serializeOpGetDocumentAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetDocumentAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetDocumentAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetDocumentAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetDocumentAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetDocumentTextDetection struct { +} + +func (*awsAwsjson11_serializeOpGetDocumentTextDetection) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetDocumentTextDetection) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetDocumentTextDetectionInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetDocumentTextDetection") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetDocumentTextDetectionInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetExpenseAnalysis struct { +} + +func (*awsAwsjson11_serializeOpGetExpenseAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetExpenseAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetExpenseAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetExpenseAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetExpenseAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetLendingAnalysis struct { +} + +func (*awsAwsjson11_serializeOpGetLendingAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetLendingAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetLendingAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetLendingAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetLendingAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetLendingAnalysisSummary struct { +} + +func (*awsAwsjson11_serializeOpGetLendingAnalysisSummary) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetLendingAnalysisSummary) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetLendingAnalysisSummaryInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.GetLendingAnalysisSummary") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetLendingAnalysisSummaryInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListAdapters struct { +} + +func (*awsAwsjson11_serializeOpListAdapters) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListAdapters) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListAdaptersInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.ListAdapters") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListAdaptersInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListAdapterVersions struct { +} + +func (*awsAwsjson11_serializeOpListAdapterVersions) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListAdapterVersions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListAdapterVersionsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.ListAdapterVersions") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListAdapterVersionsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListTagsForResource struct { +} + +func (*awsAwsjson11_serializeOpListTagsForResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListTagsForResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.ListTagsForResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListTagsForResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartDocumentAnalysis struct { +} + +func (*awsAwsjson11_serializeOpStartDocumentAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartDocumentAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartDocumentAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.StartDocumentAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartDocumentAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartDocumentTextDetection struct { +} + +func (*awsAwsjson11_serializeOpStartDocumentTextDetection) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartDocumentTextDetection) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartDocumentTextDetectionInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.StartDocumentTextDetection") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartDocumentTextDetectionInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartExpenseAnalysis struct { +} + +func (*awsAwsjson11_serializeOpStartExpenseAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartExpenseAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartExpenseAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.StartExpenseAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartExpenseAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartLendingAnalysis struct { +} + +func (*awsAwsjson11_serializeOpStartLendingAnalysis) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartLendingAnalysis) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartLendingAnalysisInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.StartLendingAnalysis") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartLendingAnalysisInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpTagResource struct { +} + +func (*awsAwsjson11_serializeOpTagResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*TagResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.TagResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentTagResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUntagResource struct { +} + +func (*awsAwsjson11_serializeOpUntagResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UntagResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.UntagResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUntagResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateAdapter struct { +} + +func (*awsAwsjson11_serializeOpUpdateAdapter) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateAdapter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateAdapterInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("Textract.UpdateAdapter") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateAdapterInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} +func awsAwsjson11_serializeDocumentAdapter(v *types.Adapter, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.Pages != nil { + ok := object.Key("Pages") + if err := awsAwsjson11_serializeDocumentAdapterPages(v.Pages, ok); err != nil { + return err + } + } + + if v.Version != nil { + ok := object.Key("Version") + ok.String(*v.Version) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAdapterPages(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentAdapters(v []types.Adapter, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentAdapter(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentAdaptersConfig(v *types.AdaptersConfig, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Adapters != nil { + ok := object.Key("Adapters") + if err := awsAwsjson11_serializeDocumentAdapters(v.Adapters, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentAdapterVersionDatasetConfig(v *types.AdapterVersionDatasetConfig, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ManifestS3Object != nil { + ok := object.Key("ManifestS3Object") + if err := awsAwsjson11_serializeDocumentS3Object(v.ManifestS3Object, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentContentClassifiers(v []types.ContentClassifier, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentDocument(v *types.Document, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Bytes != nil { + ok := object.Key("Bytes") + ok.Base64EncodeBytes(v.Bytes) + } + + if v.S3Object != nil { + ok := object.Key("S3Object") + if err := awsAwsjson11_serializeDocumentS3Object(v.S3Object, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentDocumentLocation(v *types.DocumentLocation, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.S3Object != nil { + ok := object.Key("S3Object") + if err := awsAwsjson11_serializeDocumentS3Object(v.S3Object, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentDocumentPages(v []types.Document, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentDocument(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentFeatureTypes(v []types.FeatureType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentHumanLoopConfig(v *types.HumanLoopConfig, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DataAttributes != nil { + ok := object.Key("DataAttributes") + if err := awsAwsjson11_serializeDocumentHumanLoopDataAttributes(v.DataAttributes, ok); err != nil { + return err + } + } + + if v.FlowDefinitionArn != nil { + ok := object.Key("FlowDefinitionArn") + ok.String(*v.FlowDefinitionArn) + } + + if v.HumanLoopName != nil { + ok := object.Key("HumanLoopName") + ok.String(*v.HumanLoopName) + } + + return nil +} + +func awsAwsjson11_serializeDocumentHumanLoopDataAttributes(v *types.HumanLoopDataAttributes, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ContentClassifiers != nil { + ok := object.Key("ContentClassifiers") + if err := awsAwsjson11_serializeDocumentContentClassifiers(v.ContentClassifiers, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentNotificationChannel(v *types.NotificationChannel, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.RoleArn != nil { + ok := object.Key("RoleArn") + ok.String(*v.RoleArn) + } + + if v.SNSTopicArn != nil { + ok := object.Key("SNSTopicArn") + ok.String(*v.SNSTopicArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentOutputConfig(v *types.OutputConfig, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.S3Bucket != nil { + ok := object.Key("S3Bucket") + ok.String(*v.S3Bucket) + } + + if v.S3Prefix != nil { + ok := object.Key("S3Prefix") + ok.String(*v.S3Prefix) + } + + return nil +} + +func awsAwsjson11_serializeDocumentQueries(v []types.Query, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentQuery(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentQueriesConfig(v *types.QueriesConfig, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Queries != nil { + ok := object.Key("Queries") + if err := awsAwsjson11_serializeDocumentQueries(v.Queries, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentQuery(v *types.Query, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Alias != nil { + ok := object.Key("Alias") + ok.String(*v.Alias) + } + + if v.Pages != nil { + ok := object.Key("Pages") + if err := awsAwsjson11_serializeDocumentQueryPages(v.Pages, ok); err != nil { + return err + } + } + + if v.Text != nil { + ok := object.Key("Text") + ok.String(*v.Text) + } + + return nil +} + +func awsAwsjson11_serializeDocumentQueryPages(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentS3Object(v *types.S3Object, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Bucket != nil { + ok := object.Key("Bucket") + ok.String(*v.Bucket) + } + + if v.Name != nil { + ok := object.Key("Name") + ok.String(*v.Name) + } + + if v.Version != nil { + ok := object.Key("Version") + ok.String(*v.Version) + } + + return nil +} + +func awsAwsjson11_serializeDocumentTagKeyList(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentTagMap(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeOpDocumentAnalyzeDocumentInput(v *AnalyzeDocumentInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdaptersConfig != nil { + ok := object.Key("AdaptersConfig") + if err := awsAwsjson11_serializeDocumentAdaptersConfig(v.AdaptersConfig, ok); err != nil { + return err + } + } + + if v.Document != nil { + ok := object.Key("Document") + if err := awsAwsjson11_serializeDocumentDocument(v.Document, ok); err != nil { + return err + } + } + + if v.FeatureTypes != nil { + ok := object.Key("FeatureTypes") + if err := awsAwsjson11_serializeDocumentFeatureTypes(v.FeatureTypes, ok); err != nil { + return err + } + } + + if v.HumanLoopConfig != nil { + ok := object.Key("HumanLoopConfig") + if err := awsAwsjson11_serializeDocumentHumanLoopConfig(v.HumanLoopConfig, ok); err != nil { + return err + } + } + + if v.QueriesConfig != nil { + ok := object.Key("QueriesConfig") + if err := awsAwsjson11_serializeDocumentQueriesConfig(v.QueriesConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAnalyzeExpenseInput(v *AnalyzeExpenseInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Document != nil { + ok := object.Key("Document") + if err := awsAwsjson11_serializeDocumentDocument(v.Document, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAnalyzeIDInput(v *AnalyzeIDInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DocumentPages != nil { + ok := object.Key("DocumentPages") + if err := awsAwsjson11_serializeDocumentDocumentPages(v.DocumentPages, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateAdapterInput(v *CreateAdapterInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterName != nil { + ok := object.Key("AdapterName") + ok.String(*v.AdapterName) + } + + if len(v.AutoUpdate) > 0 { + ok := object.Key("AutoUpdate") + ok.String(string(v.AutoUpdate)) + } + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.Description != nil { + ok := object.Key("Description") + ok.String(*v.Description) + } + + if v.FeatureTypes != nil { + ok := object.Key("FeatureTypes") + if err := awsAwsjson11_serializeDocumentFeatureTypes(v.FeatureTypes, ok); err != nil { + return err + } + } + + if v.Tags != nil { + ok := object.Key("Tags") + if err := awsAwsjson11_serializeDocumentTagMap(v.Tags, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateAdapterVersionInput(v *CreateAdapterVersionInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.DatasetConfig != nil { + ok := object.Key("DatasetConfig") + if err := awsAwsjson11_serializeDocumentAdapterVersionDatasetConfig(v.DatasetConfig, ok); err != nil { + return err + } + } + + if v.KMSKeyId != nil { + ok := object.Key("KMSKeyId") + ok.String(*v.KMSKeyId) + } + + if v.OutputConfig != nil { + ok := object.Key("OutputConfig") + if err := awsAwsjson11_serializeDocumentOutputConfig(v.OutputConfig, ok); err != nil { + return err + } + } + + if v.Tags != nil { + ok := object.Key("Tags") + if err := awsAwsjson11_serializeDocumentTagMap(v.Tags, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteAdapterInput(v *DeleteAdapterInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteAdapterVersionInput(v *DeleteAdapterVersionInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.AdapterVersion != nil { + ok := object.Key("AdapterVersion") + ok.String(*v.AdapterVersion) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDetectDocumentTextInput(v *DetectDocumentTextInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Document != nil { + ok := object.Key("Document") + if err := awsAwsjson11_serializeDocumentDocument(v.Document, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetAdapterInput(v *GetAdapterInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetAdapterVersionInput(v *GetAdapterVersionInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.AdapterVersion != nil { + ok := object.Key("AdapterVersion") + ok.String(*v.AdapterVersion) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetDocumentAnalysisInput(v *GetDocumentAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetDocumentTextDetectionInput(v *GetDocumentTextDetectionInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetExpenseAnalysisInput(v *GetExpenseAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetLendingAnalysisInput(v *GetLendingAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetLendingAnalysisSummaryInput(v *GetLendingAnalysisSummaryInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListAdaptersInput(v *ListAdaptersInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AfterCreationTime != nil { + ok := object.Key("AfterCreationTime") + ok.Double(smithytime.FormatEpochSeconds(*v.AfterCreationTime)) + } + + if v.BeforeCreationTime != nil { + ok := object.Key("BeforeCreationTime") + ok.Double(smithytime.FormatEpochSeconds(*v.BeforeCreationTime)) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListAdapterVersionsInput(v *ListAdapterVersionsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.AfterCreationTime != nil { + ok := object.Key("AfterCreationTime") + ok.Double(smithytime.FormatEpochSeconds(*v.AfterCreationTime)) + } + + if v.BeforeCreationTime != nil { + ok := object.Key("BeforeCreationTime") + ok.Double(smithytime.FormatEpochSeconds(*v.BeforeCreationTime)) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListTagsForResourceInput(v *ListTagsForResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceARN != nil { + ok := object.Key("ResourceARN") + ok.String(*v.ResourceARN) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartDocumentAnalysisInput(v *StartDocumentAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdaptersConfig != nil { + ok := object.Key("AdaptersConfig") + if err := awsAwsjson11_serializeDocumentAdaptersConfig(v.AdaptersConfig, ok); err != nil { + return err + } + } + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.DocumentLocation != nil { + ok := object.Key("DocumentLocation") + if err := awsAwsjson11_serializeDocumentDocumentLocation(v.DocumentLocation, ok); err != nil { + return err + } + } + + if v.FeatureTypes != nil { + ok := object.Key("FeatureTypes") + if err := awsAwsjson11_serializeDocumentFeatureTypes(v.FeatureTypes, ok); err != nil { + return err + } + } + + if v.JobTag != nil { + ok := object.Key("JobTag") + ok.String(*v.JobTag) + } + + if v.KMSKeyId != nil { + ok := object.Key("KMSKeyId") + ok.String(*v.KMSKeyId) + } + + if v.NotificationChannel != nil { + ok := object.Key("NotificationChannel") + if err := awsAwsjson11_serializeDocumentNotificationChannel(v.NotificationChannel, ok); err != nil { + return err + } + } + + if v.OutputConfig != nil { + ok := object.Key("OutputConfig") + if err := awsAwsjson11_serializeDocumentOutputConfig(v.OutputConfig, ok); err != nil { + return err + } + } + + if v.QueriesConfig != nil { + ok := object.Key("QueriesConfig") + if err := awsAwsjson11_serializeDocumentQueriesConfig(v.QueriesConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartDocumentTextDetectionInput(v *StartDocumentTextDetectionInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.DocumentLocation != nil { + ok := object.Key("DocumentLocation") + if err := awsAwsjson11_serializeDocumentDocumentLocation(v.DocumentLocation, ok); err != nil { + return err + } + } + + if v.JobTag != nil { + ok := object.Key("JobTag") + ok.String(*v.JobTag) + } + + if v.KMSKeyId != nil { + ok := object.Key("KMSKeyId") + ok.String(*v.KMSKeyId) + } + + if v.NotificationChannel != nil { + ok := object.Key("NotificationChannel") + if err := awsAwsjson11_serializeDocumentNotificationChannel(v.NotificationChannel, ok); err != nil { + return err + } + } + + if v.OutputConfig != nil { + ok := object.Key("OutputConfig") + if err := awsAwsjson11_serializeDocumentOutputConfig(v.OutputConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartExpenseAnalysisInput(v *StartExpenseAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.DocumentLocation != nil { + ok := object.Key("DocumentLocation") + if err := awsAwsjson11_serializeDocumentDocumentLocation(v.DocumentLocation, ok); err != nil { + return err + } + } + + if v.JobTag != nil { + ok := object.Key("JobTag") + ok.String(*v.JobTag) + } + + if v.KMSKeyId != nil { + ok := object.Key("KMSKeyId") + ok.String(*v.KMSKeyId) + } + + if v.NotificationChannel != nil { + ok := object.Key("NotificationChannel") + if err := awsAwsjson11_serializeDocumentNotificationChannel(v.NotificationChannel, ok); err != nil { + return err + } + } + + if v.OutputConfig != nil { + ok := object.Key("OutputConfig") + if err := awsAwsjson11_serializeDocumentOutputConfig(v.OutputConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartLendingAnalysisInput(v *StartLendingAnalysisInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientRequestToken != nil { + ok := object.Key("ClientRequestToken") + ok.String(*v.ClientRequestToken) + } + + if v.DocumentLocation != nil { + ok := object.Key("DocumentLocation") + if err := awsAwsjson11_serializeDocumentDocumentLocation(v.DocumentLocation, ok); err != nil { + return err + } + } + + if v.JobTag != nil { + ok := object.Key("JobTag") + ok.String(*v.JobTag) + } + + if v.KMSKeyId != nil { + ok := object.Key("KMSKeyId") + ok.String(*v.KMSKeyId) + } + + if v.NotificationChannel != nil { + ok := object.Key("NotificationChannel") + if err := awsAwsjson11_serializeDocumentNotificationChannel(v.NotificationChannel, ok); err != nil { + return err + } + } + + if v.OutputConfig != nil { + ok := object.Key("OutputConfig") + if err := awsAwsjson11_serializeDocumentOutputConfig(v.OutputConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentTagResourceInput(v *TagResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceARN != nil { + ok := object.Key("ResourceARN") + ok.String(*v.ResourceARN) + } + + if v.Tags != nil { + ok := object.Key("Tags") + if err := awsAwsjson11_serializeDocumentTagMap(v.Tags, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUntagResourceInput(v *UntagResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceARN != nil { + ok := object.Key("ResourceARN") + ok.String(*v.ResourceARN) + } + + if v.TagKeys != nil { + ok := object.Key("TagKeys") + if err := awsAwsjson11_serializeDocumentTagKeyList(v.TagKeys, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateAdapterInput(v *UpdateAdapterInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdapterId != nil { + ok := object.Key("AdapterId") + ok.String(*v.AdapterId) + } + + if v.AdapterName != nil { + ok := object.Key("AdapterName") + ok.String(*v.AdapterName) + } + + if len(v.AutoUpdate) > 0 { + ok := object.Key("AutoUpdate") + ok.String(string(v.AutoUpdate)) + } + + if v.Description != nil { + ok := object.Key("Description") + ok.String(*v.Description) + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/enums.go new file mode 100644 index 00000000..cc7b3090 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/enums.go @@ -0,0 +1,298 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +type AdapterVersionStatus string + +// Enum values for AdapterVersionStatus +const ( + AdapterVersionStatusActive AdapterVersionStatus = "ACTIVE" + AdapterVersionStatusAtRisk AdapterVersionStatus = "AT_RISK" + AdapterVersionStatusDeprecated AdapterVersionStatus = "DEPRECATED" + AdapterVersionStatusCreationError AdapterVersionStatus = "CREATION_ERROR" + AdapterVersionStatusCreationInProgress AdapterVersionStatus = "CREATION_IN_PROGRESS" +) + +// Values returns all known values for AdapterVersionStatus. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AdapterVersionStatus) Values() []AdapterVersionStatus { + return []AdapterVersionStatus{ + "ACTIVE", + "AT_RISK", + "DEPRECATED", + "CREATION_ERROR", + "CREATION_IN_PROGRESS", + } +} + +type AutoUpdate string + +// Enum values for AutoUpdate +const ( + AutoUpdateEnabled AutoUpdate = "ENABLED" + AutoUpdateDisabled AutoUpdate = "DISABLED" +) + +// Values returns all known values for AutoUpdate. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AutoUpdate) Values() []AutoUpdate { + return []AutoUpdate{ + "ENABLED", + "DISABLED", + } +} + +type BlockType string + +// Enum values for BlockType +const ( + BlockTypeKeyValueSet BlockType = "KEY_VALUE_SET" + BlockTypePage BlockType = "PAGE" + BlockTypeLine BlockType = "LINE" + BlockTypeWord BlockType = "WORD" + BlockTypeTable BlockType = "TABLE" + BlockTypeCell BlockType = "CELL" + BlockTypeSelectionElement BlockType = "SELECTION_ELEMENT" + BlockTypeMergedCell BlockType = "MERGED_CELL" + BlockTypeTitle BlockType = "TITLE" + BlockTypeQuery BlockType = "QUERY" + BlockTypeQueryResult BlockType = "QUERY_RESULT" + BlockTypeSignature BlockType = "SIGNATURE" + BlockTypeTableTitle BlockType = "TABLE_TITLE" + BlockTypeTableFooter BlockType = "TABLE_FOOTER" + BlockTypeLayoutText BlockType = "LAYOUT_TEXT" + BlockTypeLayoutTitle BlockType = "LAYOUT_TITLE" + BlockTypeLayoutHeader BlockType = "LAYOUT_HEADER" + BlockTypeLayoutFooter BlockType = "LAYOUT_FOOTER" + BlockTypeLayoutSectionHeader BlockType = "LAYOUT_SECTION_HEADER" + BlockTypeLayoutPageNumber BlockType = "LAYOUT_PAGE_NUMBER" + BlockTypeLayoutList BlockType = "LAYOUT_LIST" + BlockTypeLayoutFigure BlockType = "LAYOUT_FIGURE" + BlockTypeLayoutTable BlockType = "LAYOUT_TABLE" + BlockTypeLayoutKeyValue BlockType = "LAYOUT_KEY_VALUE" +) + +// Values returns all known values for BlockType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (BlockType) Values() []BlockType { + return []BlockType{ + "KEY_VALUE_SET", + "PAGE", + "LINE", + "WORD", + "TABLE", + "CELL", + "SELECTION_ELEMENT", + "MERGED_CELL", + "TITLE", + "QUERY", + "QUERY_RESULT", + "SIGNATURE", + "TABLE_TITLE", + "TABLE_FOOTER", + "LAYOUT_TEXT", + "LAYOUT_TITLE", + "LAYOUT_HEADER", + "LAYOUT_FOOTER", + "LAYOUT_SECTION_HEADER", + "LAYOUT_PAGE_NUMBER", + "LAYOUT_LIST", + "LAYOUT_FIGURE", + "LAYOUT_TABLE", + "LAYOUT_KEY_VALUE", + } +} + +type ContentClassifier string + +// Enum values for ContentClassifier +const ( + ContentClassifierFreeOfPersonallyIdentifiableInformation ContentClassifier = "FreeOfPersonallyIdentifiableInformation" + ContentClassifierFreeOfAdultContent ContentClassifier = "FreeOfAdultContent" +) + +// Values returns all known values for ContentClassifier. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ContentClassifier) Values() []ContentClassifier { + return []ContentClassifier{ + "FreeOfPersonallyIdentifiableInformation", + "FreeOfAdultContent", + } +} + +type EntityType string + +// Enum values for EntityType +const ( + EntityTypeKey EntityType = "KEY" + EntityTypeValue EntityType = "VALUE" + EntityTypeColumnHeader EntityType = "COLUMN_HEADER" + EntityTypeTableTitle EntityType = "TABLE_TITLE" + EntityTypeTableFooter EntityType = "TABLE_FOOTER" + EntityTypeTableSectionTitle EntityType = "TABLE_SECTION_TITLE" + EntityTypeTableSummary EntityType = "TABLE_SUMMARY" + EntityTypeStructuredTable EntityType = "STRUCTURED_TABLE" + EntityTypeSemiStructuredTable EntityType = "SEMI_STRUCTURED_TABLE" +) + +// Values returns all known values for EntityType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EntityType) Values() []EntityType { + return []EntityType{ + "KEY", + "VALUE", + "COLUMN_HEADER", + "TABLE_TITLE", + "TABLE_FOOTER", + "TABLE_SECTION_TITLE", + "TABLE_SUMMARY", + "STRUCTURED_TABLE", + "SEMI_STRUCTURED_TABLE", + } +} + +type FeatureType string + +// Enum values for FeatureType +const ( + FeatureTypeTables FeatureType = "TABLES" + FeatureTypeForms FeatureType = "FORMS" + FeatureTypeQueries FeatureType = "QUERIES" + FeatureTypeSignatures FeatureType = "SIGNATURES" + FeatureTypeLayout FeatureType = "LAYOUT" +) + +// Values returns all known values for FeatureType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (FeatureType) Values() []FeatureType { + return []FeatureType{ + "TABLES", + "FORMS", + "QUERIES", + "SIGNATURES", + "LAYOUT", + } +} + +type JobStatus string + +// Enum values for JobStatus +const ( + JobStatusInProgress JobStatus = "IN_PROGRESS" + JobStatusSucceeded JobStatus = "SUCCEEDED" + JobStatusFailed JobStatus = "FAILED" + JobStatusPartialSuccess JobStatus = "PARTIAL_SUCCESS" +) + +// Values returns all known values for JobStatus. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (JobStatus) Values() []JobStatus { + return []JobStatus{ + "IN_PROGRESS", + "SUCCEEDED", + "FAILED", + "PARTIAL_SUCCESS", + } +} + +type RelationshipType string + +// Enum values for RelationshipType +const ( + RelationshipTypeValue RelationshipType = "VALUE" + RelationshipTypeChild RelationshipType = "CHILD" + RelationshipTypeComplexFeatures RelationshipType = "COMPLEX_FEATURES" + RelationshipTypeMergedCell RelationshipType = "MERGED_CELL" + RelationshipTypeTitle RelationshipType = "TITLE" + RelationshipTypeAnswer RelationshipType = "ANSWER" + RelationshipTypeTable RelationshipType = "TABLE" + RelationshipTypeTableTitle RelationshipType = "TABLE_TITLE" + RelationshipTypeTableFooter RelationshipType = "TABLE_FOOTER" +) + +// Values returns all known values for RelationshipType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (RelationshipType) Values() []RelationshipType { + return []RelationshipType{ + "VALUE", + "CHILD", + "COMPLEX_FEATURES", + "MERGED_CELL", + "TITLE", + "ANSWER", + "TABLE", + "TABLE_TITLE", + "TABLE_FOOTER", + } +} + +type SelectionStatus string + +// Enum values for SelectionStatus +const ( + SelectionStatusSelected SelectionStatus = "SELECTED" + SelectionStatusNotSelected SelectionStatus = "NOT_SELECTED" +) + +// Values returns all known values for SelectionStatus. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (SelectionStatus) Values() []SelectionStatus { + return []SelectionStatus{ + "SELECTED", + "NOT_SELECTED", + } +} + +type TextType string + +// Enum values for TextType +const ( + TextTypeHandwriting TextType = "HANDWRITING" + TextTypePrinted TextType = "PRINTED" +) + +// Values returns all known values for TextType. Note that this can be expanded in +// the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (TextType) Values() []TextType { + return []TextType{ + "HANDWRITING", + "PRINTED", + } +} + +type ValueType string + +// Enum values for ValueType +const ( + ValueTypeDate ValueType = "DATE" +) + +// Values returns all known values for ValueType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ValueType) Values() []ValueType { + return []ValueType{ + "DATE", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/errors.go new file mode 100644 index 00000000..96c16b53 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/errors.go @@ -0,0 +1,543 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + "fmt" + smithy "github.com/aws/smithy-go" +) + +// You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) +// of an authorized user or IAM role to perform the operation. +type AccessDeniedException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *AccessDeniedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *AccessDeniedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "AccessDeniedException" + } + return *e.ErrorCodeOverride +} +func (e *AccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Amazon Textract isn't able to read the document. For more information on the +// document limits in Amazon Textract, see limits. +type BadDocumentException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *BadDocumentException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *BadDocumentException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *BadDocumentException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "BadDocumentException" + } + return *e.ErrorCodeOverride +} +func (e *BadDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Updating or deleting a resource can cause an inconsistent state. +type ConflictException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ConflictException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ConflictException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ConflictException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ConflictException" + } + return *e.ErrorCodeOverride +} +func (e *ConflictException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The document can't be processed because it's too large. The maximum document +// size for synchronous operations 10 MB. The maximum document size for +// asynchronous operations is 500 MB for PDF files. +type DocumentTooLargeException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *DocumentTooLargeException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *DocumentTooLargeException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *DocumentTooLargeException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "DocumentTooLargeException" + } + return *e.ErrorCodeOverride +} +func (e *DocumentTooLargeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Indicates you have exceeded the maximum number of active human in the loop +// workflows available +type HumanLoopQuotaExceededException struct { + Message *string + + ErrorCodeOverride *string + + ResourceType *string + QuotaCode *string + ServiceCode *string + Code *string + + noSmithyDocumentSerde +} + +func (e *HumanLoopQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *HumanLoopQuotaExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *HumanLoopQuotaExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "HumanLoopQuotaExceededException" + } + return *e.ErrorCodeOverride +} +func (e *HumanLoopQuotaExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// A ClientRequestToken input parameter was reused with an operation, but at least +// one of the other input parameters is different from the previous call to the +// operation. +type IdempotentParameterMismatchException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *IdempotentParameterMismatchException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *IdempotentParameterMismatchException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *IdempotentParameterMismatchException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "IdempotentParameterMismatchException" + } + return *e.ErrorCodeOverride +} +func (e *IdempotentParameterMismatchException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// Amazon Textract experienced a service issue. Try your call again. +type InternalServerError struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *InternalServerError) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InternalServerError) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InternalServerError) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InternalServerError" + } + return *e.ErrorCodeOverride +} +func (e *InternalServerError) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } + +// An invalid job identifier was passed to an asynchronous analysis operation. +type InvalidJobIdException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *InvalidJobIdException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidJobIdException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidJobIdException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidJobIdException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidJobIdException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Indicates you do not have decrypt permissions with the KMS key entered, or the +// +// KMS key was entered incorrectly. +type InvalidKMSKeyException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *InvalidKMSKeyException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidKMSKeyException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidKMSKeyException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidKMSKeyException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidKMSKeyException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// An input parameter violated a constraint. For example, in synchronous +// operations, an InvalidParameterException exception occurs when neither of the +// S3Object or Bytes values are supplied in the Document request parameter. +// Validate your parameter before calling the API operation again. +type InvalidParameterException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *InvalidParameterException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidParameterException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidParameterException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidParameterException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidParameterException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Amazon Textract is unable to access the S3 object that's specified in the +// request. for more information, [Configure Access to Amazon S3]For troubleshooting information, see [Troubleshooting Amazon S3] +// +// [Troubleshooting Amazon S3]: https://docs.aws.amazon.com/AmazonS3/latest/dev/troubleshooting.html +// [Configure Access to Amazon S3]: https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html +type InvalidS3ObjectException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *InvalidS3ObjectException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidS3ObjectException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidS3ObjectException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidS3ObjectException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidS3ObjectException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// An Amazon Textract service limit was exceeded. For example, if you start too +// many asynchronous jobs concurrently, calls to start operations ( +// StartDocumentTextDetection , for example) raise a LimitExceededException +// exception (HTTP status code: 400) until the number of concurrently running jobs +// is below the Amazon Textract service limit. +type LimitExceededException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *LimitExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *LimitExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *LimitExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "LimitExceededException" + } + return *e.ErrorCodeOverride +} +func (e *LimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The number of requests exceeded your throughput limit. If you want to increase +// this limit, contact Amazon Textract. +type ProvisionedThroughputExceededException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ProvisionedThroughputExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ProvisionedThroughputExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ProvisionedThroughputExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ProvisionedThroughputExceededException" + } + return *e.ErrorCodeOverride +} +func (e *ProvisionedThroughputExceededException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// Returned when an operation tried to access a nonexistent resource. +type ResourceNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ResourceNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ResourceNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ResourceNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Returned when a request cannot be completed as it would exceed a maximum +// service quota. +type ServiceQuotaExceededException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ServiceQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ServiceQuotaExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ServiceQuotaExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ServiceQuotaExceededException" + } + return *e.ErrorCodeOverride +} +func (e *ServiceQuotaExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Amazon Textract is temporarily unable to process the request. Try your call +// again. +type ThrottlingException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ThrottlingException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ThrottlingException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ThrottlingException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ThrottlingException" + } + return *e.ErrorCodeOverride +} +func (e *ThrottlingException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } + +// The format of the input document isn't supported. Documents for operations can +// be in PNG, JPEG, PDF, or TIFF format. +type UnsupportedDocumentException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *UnsupportedDocumentException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnsupportedDocumentException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnsupportedDocumentException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnsupportedDocumentException" + } + return *e.ErrorCodeOverride +} +func (e *UnsupportedDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Indicates that a request was not valid. Check request for proper formatting. +type ValidationException struct { + Message *string + + ErrorCodeOverride *string + + Code *string + + noSmithyDocumentSerde +} + +func (e *ValidationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ValidationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ValidationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ValidationException" + } + return *e.ErrorCodeOverride +} +func (e *ValidationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/types.go new file mode 100644 index 00000000..1b77c5a6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/types/types.go @@ -0,0 +1,1103 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + smithydocument "github.com/aws/smithy-go/document" + "time" +) + +// An adapter selected for use when analyzing documents. Contains an adapter ID +// and a version number. Contains information on pages selected for analysis when +// analyzing documents asychronously. +type Adapter struct { + + // A unique identifier for the adapter resource. + // + // This member is required. + AdapterId *string + + // A string that identifies the version of the adapter. + // + // This member is required. + Version *string + + // Pages is a parameter that the user inputs to specify which pages to apply an + // adapter to. The following is a list of rules for using this parameter. + // + // - If a page is not specified, it is set to ["1"] by default. + // + // - The following characters are allowed in the parameter's string: 0 1 2 3 4 5 + // 6 7 8 9 - * . No whitespace is allowed. + // + // - When using * to indicate all pages, it must be the only element in the list. + // + // - You can use page intervals, such as ["1-3", "1-1", "4-*"] . Where * + // indicates last page of document. + // + // - Specified pages must be greater than 0 and less than or equal to the number + // of pages in the document. + Pages []string + + noSmithyDocumentSerde +} + +// Contains information on the adapter, including the adapter ID, Name, Creation +// time, and feature types. +type AdapterOverview struct { + + // A unique identifier for the adapter resource. + AdapterId *string + + // A string naming the adapter resource. + AdapterName *string + + // The date and time that the adapter was created. + CreationTime *time.Time + + // The feature types that the adapter is operating on. + FeatureTypes []FeatureType + + noSmithyDocumentSerde +} + +// Contains information about adapters used when analyzing a document, with each +// adapter specified using an AdapterId and version +type AdaptersConfig struct { + + // A list of adapters to be used when analyzing the specified document. + // + // This member is required. + Adapters []Adapter + + noSmithyDocumentSerde +} + +// The dataset configuration options for a given version of an adapter. Can +// include an Amazon S3 bucket if specified. +type AdapterVersionDatasetConfig struct { + + // The S3 bucket name and file name that identifies the document. + // + // The AWS Region for the S3 bucket that contains the document must match the + // Region that you use for Amazon Textract operations. + // + // For Amazon Textract to process a file in an S3 bucket, the user must have + // permission to access the S3 bucket and file. + ManifestS3Object *S3Object + + noSmithyDocumentSerde +} + +// Contains information on the metrics used to evalute the peformance of a given +// adapter version. Includes data for baseline model performance and individual +// adapter version perfromance. +type AdapterVersionEvaluationMetric struct { + + // The F1 score, precision, and recall metrics for the baseline model. + AdapterVersion *EvaluationMetric + + // The F1 score, precision, and recall metrics for the baseline model. + Baseline *EvaluationMetric + + // Indicates the feature type being analyzed by a given adapter version. + FeatureType FeatureType + + noSmithyDocumentSerde +} + +// Summary info for an adapter version. Contains information on the AdapterId, +// AdapterVersion, CreationTime, FeatureTypes, and Status. +type AdapterVersionOverview struct { + + // A unique identifier for the adapter associated with a given adapter version. + AdapterId *string + + // An identified for a given adapter version. + AdapterVersion *string + + // The date and time that a given adapter version was created. + CreationTime *time.Time + + // The feature types that the adapter version is operating on. + FeatureTypes []FeatureType + + // Contains information on the status of a given adapter version. + Status AdapterVersionStatus + + // A message explaining the status of a given adapter vesion. + StatusMessage *string + + noSmithyDocumentSerde +} + +// Used to contain the information detected by an AnalyzeID operation. +type AnalyzeIDDetections struct { + + // Text of either the normalized field or value associated with it. + // + // This member is required. + Text *string + + // The confidence score of the detected text. + Confidence *float32 + + // Only returned for dates, returns the type of value detected and the date + // written in a more machine readable way. + NormalizedValue *NormalizedValue + + noSmithyDocumentSerde +} + +// A Block represents items that are recognized in a document within a group of +// pixels close to each other. The information returned in a Block object depends +// on the type of operation. In text detection for documents (for example DetectDocumentText), you +// get information about the detected words and lines of text. In text analysis +// (for example AnalyzeDocument), you can also get information about the fields, tables, and +// selection elements that are detected in the document. +// +// An array of Block objects is returned by both synchronous and asynchronous +// operations. In synchronous operations, such as DetectDocumentText, the array of Block objects is +// the entire set of results. In asynchronous operations, such as GetDocumentAnalysis, the array is +// returned over one or more responses. +// +// For more information, see [How Amazon Textract Works]. +// +// [How Amazon Textract Works]: https://docs.aws.amazon.com/textract/latest/dg/how-it-works.html +type Block struct { + + // The type of text item that's recognized. In operations for text detection, the + // following types are returned: + // + // - PAGE - Contains a list of the LINE Block objects that are detected on a + // document page. + // + // - WORD - A word detected on a document page. A word is one or more ISO basic + // Latin script characters that aren't separated by spaces. + // + // - LINE - A string of tab-delimited, contiguous words that are detected on a + // document page. + // + // In text analysis operations, the following types are returned: + // + // - PAGE - Contains a list of child Block objects that are detected on a + // document page. + // + // - KEY_VALUE_SET - Stores the KEY and VALUE Block objects for linked text + // that's detected on a document page. Use the EntityType field to determine if a + // KEY_VALUE_SET object is a KEY Block object or a VALUE Block object. + // + // - WORD - A word that's detected on a document page. A word is one or more ISO + // basic Latin script characters that aren't separated by spaces. + // + // - LINE - A string of tab-delimited, contiguous words that are detected on a + // document page. + // + // - TABLE - A table that's detected on a document page. A table is grid-based + // information with two or more rows or columns, with a cell span of one row and + // one column each. + // + // - TABLE_TITLE - The title of a table. A title is typically a line of text + // above or below a table, or embedded as the first row of a table. + // + // - TABLE_FOOTER - The footer associated with a table. A footer is typically a + // line or lines of text below a table or embedded as the last row of a table. + // + // - CELL - A cell within a detected table. The cell is the parent of the block + // that contains the text in the cell. + // + // - MERGED_CELL - A cell in a table whose content spans more than one row or + // column. The Relationships array for this cell contain data from individual + // cells. + // + // - SELECTION_ELEMENT - A selection element such as an option button (radio + // button) or a check box that's detected on a document page. Use the value of + // SelectionStatus to determine the status of the selection element. + // + // - SIGNATURE - The location and confidence score of a signature detected on a + // document page. Can be returned as part of a Key-Value pair or a detected cell. + // + // - QUERY - A question asked during the call of AnalyzeDocument. Contains an + // alias and an ID that attaches it to its answer. + // + // - QUERY_RESULT - A response to a question asked during the call of analyze + // document. Comes with an alias and ID for ease of locating in a response. Also + // contains location and confidence score. + // + // The following BlockTypes are only returned for Amazon Textract Layout. + // + // - LAYOUT_TITLE - The main title of the document. + // + // - LAYOUT_HEADER - Text located in the top margin of the document. + // + // - LAYOUT_FOOTER - Text located in the bottom margin of the document. + // + // - LAYOUT_SECTION_HEADER - The titles of sections within a document. + // + // - LAYOUT_PAGE_NUMBER - The page number of the documents. + // + // - LAYOUT_LIST - Any information grouped together in list form. + // + // - LAYOUT_FIGURE - Indicates the location of an image in a document. + // + // - LAYOUT_TABLE - Indicates the location of a table in the document. + // + // - LAYOUT_KEY_VALUE - Indicates the location of form key-values in a document. + // + // - LAYOUT_TEXT - Text that is present typically as a part of paragraphs in + // documents. + BlockType BlockType + + // The column in which a table cell appears. The first column position is 1. + // ColumnIndex isn't returned by DetectDocumentText and GetDocumentTextDetection . + ColumnIndex *int32 + + // The number of columns that a table cell spans. ColumnSpan isn't returned by + // DetectDocumentText and GetDocumentTextDetection . + ColumnSpan *int32 + + // The confidence score that Amazon Textract has in the accuracy of the recognized + // text and the accuracy of the geometry points around the recognized text. + Confidence *float32 + + // The type of entity. + // + // The following entity types can be returned by FORMS analysis: + // + // - KEY - An identifier for a field on the document. + // + // - VALUE - The field text. + // + // The following entity types can be returned by TABLES analysis: + // + // - COLUMN_HEADER - Identifies a cell that is a header of a column. + // + // - TABLE_TITLE - Identifies a cell that is a title within the table. + // + // - TABLE_SECTION_TITLE - Identifies a cell that is a title of a section within + // a table. A section title is a cell that typically spans an entire row above a + // section. + // + // - TABLE_FOOTER - Identifies a cell that is a footer of a table. + // + // - TABLE_SUMMARY - Identifies a summary cell of a table. A summary cell can be + // a row of a table or an additional, smaller table that contains summary + // information for another table. + // + // - STRUCTURED_TABLE - Identifies a table with column headers where the content + // of each row corresponds to the headers. + // + // - SEMI_STRUCTURED_TABLE - Identifies a non-structured table. + // + // EntityTypes isn't returned by DetectDocumentText and GetDocumentTextDetection . + EntityTypes []EntityType + + // The location of the recognized text on the image. It includes an axis-aligned, + // coarse bounding box that surrounds the text, and a finer-grain polygon for more + // accurate spatial information. + Geometry *Geometry + + // The identifier for the recognized text. The identifier is only unique for a + // single operation. + Id *string + + // The page on which a block was detected. Page is returned by synchronous and + // asynchronous operations. Page values greater than 1 are only returned for + // multipage documents that are in PDF or TIFF format. A scanned image (JPEG/PNG) + // provided to an asynchronous operation, even if it contains multiple document + // pages, is considered a single-page document. This means that for scanned images + // the value of Page is always 1. + Page *int32 + + // + Query *Query + + // A list of relationship objects that describe how blocks are related to each + // other. For example, a LINE block object contains a CHILD relationship type with + // the WORD blocks that make up the line of text. There aren't Relationship objects + // in the list for relationships that don't exist, such as when the current block + // has no child blocks. + Relationships []Relationship + + // The row in which a table cell is located. The first row position is 1. RowIndex + // isn't returned by DetectDocumentText and GetDocumentTextDetection . + RowIndex *int32 + + // The number of rows that a table cell spans. RowSpan isn't returned by + // DetectDocumentText and GetDocumentTextDetection . + RowSpan *int32 + + // The selection status of a selection element, such as an option button or check + // box. + SelectionStatus SelectionStatus + + // The word or line of text that's recognized by Amazon Textract. + Text *string + + // The kind of text that Amazon Textract has detected. Can check for handwritten + // text and printed text. + TextType TextType + + noSmithyDocumentSerde +} + +// The bounding box around the detected page, text, key-value pair, table, table +// cell, or selection element on a document page. The left (x-coordinate) and top +// (y-coordinate) are coordinates that represent the top and left sides of the +// bounding box. Note that the upper-left corner of the image is the origin (0,0). +// +// The top and left values returned are ratios of the overall document page size. +// For example, if the input image is 700 x 200 pixels, and the top-left coordinate +// of the bounding box is 350 x 50 pixels, the API returns a left value of 0.5 +// (350/700) and a top value of 0.25 (50/200). +// +// The width and height values represent the dimensions of the bounding box as a +// ratio of the overall document page dimension. For example, if the document page +// size is 700 x 200 pixels, and the bounding box width is 70 pixels, the width +// returned is 0.1. +type BoundingBox struct { + + // The height of the bounding box as a ratio of the overall document page height. + Height float32 + + // The left coordinate of the bounding box as a ratio of overall document page + // width. + Left float32 + + // The top coordinate of the bounding box as a ratio of overall document page + // height. + Top float32 + + // The width of the bounding box as a ratio of the overall document page width. + Width float32 + + noSmithyDocumentSerde +} + +// A structure that holds information regarding a detected signature on a page. +type DetectedSignature struct { + + // The page a detected signature was found on. + Page *int32 + + noSmithyDocumentSerde +} + +// The input document, either as bytes or as an S3 object. +// +// You pass image bytes to an Amazon Textract API operation by using the Bytes +// property. For example, you would use the Bytes property to pass a document +// loaded from a local file system. Image bytes passed by using the Bytes property +// must be base64 encoded. Your code might not need to encode document file bytes +// if you're using an AWS SDK to call Amazon Textract API operations. +// +// You pass images stored in an S3 bucket to an Amazon Textract API operation by +// using the S3Object property. Documents stored in an S3 bucket don't need to be +// base64 encoded. +// +// The AWS Region for the S3 bucket that contains the S3 object must match the AWS +// Region that you use for Amazon Textract operations. +// +// If you use the AWS CLI to call Amazon Textract operations, passing image bytes +// using the Bytes property isn't supported. You must first upload the document to +// an Amazon S3 bucket, and then call the operation using the S3Object property. +// +// For Amazon Textract to process an S3 object, the user must have permission to +// access the S3 object. +type Document struct { + + // A blob of base64-encoded document bytes. The maximum size of a document that's + // provided in a blob of bytes is 5 MB. The document bytes must be in PNG or JPEG + // format. + // + // If you're using an AWS SDK to call Amazon Textract, you might not need to + // base64-encode image bytes passed using the Bytes field. + Bytes []byte + + // Identifies an S3 object as the document source. The maximum size of a document + // that's stored in an S3 bucket is 5 MB. + S3Object *S3Object + + noSmithyDocumentSerde +} + +// Summary information about documents grouped by the same document type. +type DocumentGroup struct { + + // A list of the detected signatures found in a document group. + DetectedSignatures []DetectedSignature + + // An array that contains information about the pages of a document, defined by + // logical boundary. + SplitDocuments []SplitDocument + + // The type of document that Amazon Textract has detected. See [Analyze Lending Response Objects] for a list of all + // types returned by Textract. + // + // [Analyze Lending Response Objects]: https://docs.aws.amazon.com/textract/latest/dg/lending-response-objects.html + Type *string + + // A list of any expected signatures not found in a document group. + UndetectedSignatures []UndetectedSignature + + noSmithyDocumentSerde +} + +// The Amazon S3 bucket that contains the document to be processed. It's used by +// asynchronous operations. +// +// The input document can be an image file in JPEG or PNG format. It can also be a +// file in PDF format. +type DocumentLocation struct { + + // The Amazon S3 bucket that contains the input document. + S3Object *S3Object + + noSmithyDocumentSerde +} + +// Information about the input document. +type DocumentMetadata struct { + + // The number of pages that are detected in the document. + Pages *int32 + + noSmithyDocumentSerde +} + +// The evaluation metrics (F1 score, Precision, and Recall) for an adapter version. +type EvaluationMetric struct { + + // The F1 score for an adapter version. + F1Score float32 + + // The Precision score for an adapter version. + Precision float32 + + // The Recall score for an adapter version. + Recall float32 + + noSmithyDocumentSerde +} + +// Returns the kind of currency detected. +type ExpenseCurrency struct { + + // Currency code for detected currency. the current supported codes are: + // + // - USD + // + // - EUR + // + // - GBP + // + // - CAD + // + // - INR + // + // - JPY + // + // - CHF + // + // - AUD + // + // - CNY + // + // - BZR + // + // - SEK + // + // - HKD + Code *string + + // Percentage confideence in the detected currency. + Confidence *float32 + + noSmithyDocumentSerde +} + +// An object used to store information about the Value or Label detected by Amazon +// Textract. +type ExpenseDetection struct { + + // The confidence in detection, as a percentage + Confidence *float32 + + // Information about where the following items are located on a document page: + // detected page, text, key-value pairs, tables, table cells, and selection + // elements. + Geometry *Geometry + + // The word or line of text recognized by Amazon Textract + Text *string + + noSmithyDocumentSerde +} + +// The structure holding all the information returned by AnalyzeExpense +type ExpenseDocument struct { + + // This is a block object, the same as reported when DetectDocumentText is run on + // a document. It provides word level recognition of text. + Blocks []Block + + // Denotes which invoice or receipt in the document the information is coming + // from. First document will be 1, the second 2, and so on. + ExpenseIndex *int32 + + // Information detected on each table of a document, seperated into LineItems . + LineItemGroups []LineItemGroup + + // Any information found outside of a table by Amazon Textract. + SummaryFields []ExpenseField + + noSmithyDocumentSerde +} + +// Breakdown of detected information, seperated into the catagories Type, +// LabelDetection, and ValueDetection +type ExpenseField struct { + + // Shows the kind of currency, both the code and confidence associated with any + // monatary value detected. + Currency *ExpenseCurrency + + // Shows which group a response object belongs to, such as whether an address line + // belongs to the vendor's address or the recipent's address. + GroupProperties []ExpenseGroupProperty + + // The explicitly stated label of a detected element. + LabelDetection *ExpenseDetection + + // The page number the value was detected on. + PageNumber *int32 + + // The implied label of a detected element. Present alongside LabelDetection for + // explicit elements. + Type *ExpenseType + + // The value of a detected element. Present in explicit and implicit elements. + ValueDetection *ExpenseDetection + + noSmithyDocumentSerde +} + +// Shows the group that a certain key belongs to. This helps differentiate between +// names and addresses for different organizations, that can be hard to determine +// via JSON response. +type ExpenseGroupProperty struct { + + // Provides a group Id number, which will be the same for each in the group. + Id *string + + // Informs you on whether the expense group is a name or an address. + Types []string + + noSmithyDocumentSerde +} + +// An object used to store information about the Type detected by Amazon Textract. +type ExpenseType struct { + + // The confidence of accuracy, as a percentage. + Confidence *float32 + + // The word or line of text detected by Amazon Textract. + Text *string + + noSmithyDocumentSerde +} + +// Contains information extracted by an analysis operation after using +// StartLendingAnalysis. +type Extraction struct { + + // The structure holding all the information returned by AnalyzeExpense + ExpenseDocument *ExpenseDocument + + // The structure that lists each document processed in an AnalyzeID operation. + IdentityDocument *IdentityDocument + + // Holds the structured data returned by AnalyzeDocument for lending documents. + LendingDocument *LendingDocument + + noSmithyDocumentSerde +} + +// Information about where the following items are located on a document page: +// detected page, text, key-value pairs, tables, table cells, and selection +// elements. +type Geometry struct { + + // An axis-aligned coarse representation of the location of the recognized item on + // the document page. + BoundingBox *BoundingBox + + // Within the bounding box, a fine-grained polygon around the recognized item. + Polygon []Point + + noSmithyDocumentSerde +} + +// Shows the results of the human in the loop evaluation. If there is no +// HumanLoopArn, the input did not trigger human review. +type HumanLoopActivationOutput struct { + + // Shows the result of condition evaluations, including those conditions which + // activated a human review. + // + // This value conforms to the media type: application/json + HumanLoopActivationConditionsEvaluationResults *string + + // Shows if and why human review was needed. + HumanLoopActivationReasons []string + + // The Amazon Resource Name (ARN) of the HumanLoop created. + HumanLoopArn *string + + noSmithyDocumentSerde +} + +// Sets up the human review workflow the document will be sent to if one of the +// conditions is met. You can also set certain attributes of the image before +// review. +type HumanLoopConfig struct { + + // The Amazon Resource Name (ARN) of the flow definition. + // + // This member is required. + FlowDefinitionArn *string + + // The name of the human workflow used for this image. This should be kept unique + // within a region. + // + // This member is required. + HumanLoopName *string + + // Sets attributes of the input data. + DataAttributes *HumanLoopDataAttributes + + noSmithyDocumentSerde +} + +// Allows you to set attributes of the image. Currently, you can declare an image +// as free of personally identifiable information and adult content. +type HumanLoopDataAttributes struct { + + // Sets whether the input image is free of personally identifiable information or + // adult content. + ContentClassifiers []ContentClassifier + + noSmithyDocumentSerde +} + +// The structure that lists each document processed in an AnalyzeID operation. +type IdentityDocument struct { + + // Individual word recognition, as returned by document detection. + Blocks []Block + + // Denotes the placement of a document in the IdentityDocument list. The first + // document is marked 1, the second 2 and so on. + DocumentIndex *int32 + + // The structure used to record information extracted from identity documents. + // Contains both normalized field and value of the extracted text. + IdentityDocumentFields []IdentityDocumentField + + noSmithyDocumentSerde +} + +// Structure containing both the normalized type of the extracted information and +// the text associated with it. These are extracted as Type and Value respectively. +type IdentityDocumentField struct { + + // Used to contain the information detected by an AnalyzeID operation. + Type *AnalyzeIDDetections + + // Used to contain the information detected by an AnalyzeID operation. + ValueDetection *AnalyzeIDDetections + + noSmithyDocumentSerde +} + +// The results extracted for a lending document. +type LendingDetection struct { + + // The confidence level for the text of a detected value in a lending document. + Confidence *float32 + + // Information about where the following items are located on a document page: + // detected page, text, key-value pairs, tables, table cells, and selection + // elements. + Geometry *Geometry + + // The selection status of a selection element, such as an option button or check + // box. + SelectionStatus SelectionStatus + + // The text extracted for a detected value in a lending document. + Text *string + + noSmithyDocumentSerde +} + +// Holds the structured data returned by AnalyzeDocument for lending documents. +type LendingDocument struct { + + // An array of LendingField objects. + LendingFields []LendingField + + // A list of signatures detected in a lending document. + SignatureDetections []SignatureDetection + + noSmithyDocumentSerde +} + +// Holds the normalized key-value pairs returned by AnalyzeDocument, including the +// document type, detected text, and geometry. +type LendingField struct { + + // The results extracted for a lending document. + KeyDetection *LendingDetection + + // The type of the lending document. + Type *string + + // An array of LendingDetection objects. + ValueDetections []LendingDetection + + noSmithyDocumentSerde +} + +// Contains the detections for each page analyzed through the Analyze Lending API. +type LendingResult struct { + + // An array of Extraction to hold structured data. e.g. normalized key value pairs + // instead of raw OCR detections . + Extractions []Extraction + + // The page number for a page, with regard to whole submission. + Page *int32 + + // The classifier result for a given page. + PageClassification *PageClassification + + noSmithyDocumentSerde +} + +// Contains information regarding DocumentGroups and UndetectedDocumentTypes. +type LendingSummary struct { + + // Contains an array of all DocumentGroup objects. + DocumentGroups []DocumentGroup + + // UndetectedDocumentTypes. + UndetectedDocumentTypes []string + + noSmithyDocumentSerde +} + +// A structure that holds information about the different lines found in a +// document's tables. +type LineItemFields struct { + + // ExpenseFields used to show information from detected lines on a table. + LineItemExpenseFields []ExpenseField + + noSmithyDocumentSerde +} + +// A grouping of tables which contain LineItems, with each table identified by the +// table's LineItemGroupIndex . +type LineItemGroup struct { + + // The number used to identify a specific table in a document. The first table + // encountered will have a LineItemGroupIndex of 1, the second 2, etc. + LineItemGroupIndex *int32 + + // The breakdown of information on a particular line of a table. + LineItems []LineItemFields + + noSmithyDocumentSerde +} + +// Contains information relating to dates in a document, including the type of +// value, and the value. +type NormalizedValue struct { + + // The value of the date, written as Year-Month-DayTHour:Minute:Second. + Value *string + + // The normalized type of the value detected. In this case, DATE. + ValueType ValueType + + noSmithyDocumentSerde +} + +// The Amazon Simple Notification Service (Amazon SNS) topic to which Amazon +// Textract publishes the completion status of an asynchronous document operation. +type NotificationChannel struct { + + // The Amazon Resource Name (ARN) of an IAM role that gives Amazon Textract + // publishing permissions to the Amazon SNS topic. + // + // This member is required. + RoleArn *string + + // The Amazon SNS topic that Amazon Textract posts the completion status to. + // + // This member is required. + SNSTopicArn *string + + noSmithyDocumentSerde +} + +// Sets whether or not your output will go to a user created bucket. Used to set +// the name of the bucket, and the prefix on the output file. +// +// OutputConfig is an optional parameter which lets you adjust where your output +// will be placed. By default, Amazon Textract will store the results internally +// and can only be accessed by the Get API operations. With OutputConfig enabled, +// you can set the name of the bucket the output will be sent to the file prefix of +// the results where you can download your results. Additionally, you can set the +// KMSKeyID parameter to a customer master key (CMK) to encrypt your output. +// Without this parameter set Amazon Textract will encrypt server-side using the +// AWS managed CMK for Amazon S3. +// +// Decryption of Customer Content is necessary for processing of the documents by +// Amazon Textract. If your account is opted out under an AI services opt out +// policy then all unencrypted Customer Content is immediately and permanently +// deleted after the Customer Content has been processed by the service. No copy of +// of the output is retained by Amazon Textract. For information about how to opt +// out, see [Managing AI services opt-out policy.] +// +// For more information on data privacy, see the [Data Privacy FAQ]. +// +// [Managing AI services opt-out policy.]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html +// [Data Privacy FAQ]: https://aws.amazon.com/compliance/data-privacy-faq/ +type OutputConfig struct { + + // The name of the bucket your output will go to. + // + // This member is required. + S3Bucket *string + + // The prefix of the object key that the output will be saved to. When not + // enabled, the prefix will be “textract_output". + S3Prefix *string + + noSmithyDocumentSerde +} + +// The class assigned to a Page object detected in an input document. Contains +// information regarding the predicted type/class of a document's page and the page +// number that the Page object was detected on. +type PageClassification struct { + + // The page number the value was detected on, relative to Amazon Textract's + // starting position. + // + // This member is required. + PageNumber []Prediction + + // The class, or document type, assigned to a detected Page object. The class, or + // document type, assigned to a detected Page object. + // + // This member is required. + PageType []Prediction + + noSmithyDocumentSerde +} + +// The X and Y coordinates of a point on a document page. The X and Y values that +// are returned are ratios of the overall document page size. For example, if the +// input document is 700 x 200 and the operation returns X=0.5 and Y=0.25, then the +// point is at the (350,50) pixel coordinate on the document page. +// +// An array of Point objects, Polygon , is returned by DetectDocumentText. Polygon represents a +// fine-grained polygon around detected text. For more information, see Geometry in +// the Amazon Textract Developer Guide. +type Point struct { + + // The value of the X coordinate for a point on a Polygon . + X float32 + + // The value of the Y coordinate for a point on a Polygon . + Y float32 + + noSmithyDocumentSerde +} + +// Contains information regarding predicted values returned by Amazon Textract +// operations, including the predicted value and the confidence in the predicted +// value. +type Prediction struct { + + // Amazon Textract's confidence in its predicted value. + Confidence *float32 + + // The predicted value of a detected object. + Value *string + + noSmithyDocumentSerde +} + +type QueriesConfig struct { + + // + // + // This member is required. + Queries []Query + + noSmithyDocumentSerde +} + +// Each query contains the question you want to ask in the Text and the alias you +// want to associate. +type Query struct { + + // Question that Amazon Textract will apply to the document. An example would be + // "What is the customer's SSN?" + // + // This member is required. + Text *string + + // Alias attached to the query, for ease of location. + Alias *string + + // Pages is a parameter that the user inputs to specify which pages to apply a + // query to. The following is a list of rules for using this parameter. + // + // - If a page is not specified, it is set to ["1"] by default. + // + // - The following characters are allowed in the parameter's string: 0 1 2 3 4 5 + // 6 7 8 9 - * . No whitespace is allowed. + // + // - When using * to indicate all pages, it must be the only element in the list. + // + // - You can use page intervals, such as [“1-3”, “1-1”, “4-*”] . Where * + // indicates last page of document. + // + // - Specified pages must be greater than 0 and less than or equal to the number + // of pages in the document. + Pages []string + + noSmithyDocumentSerde +} + +// Information about how blocks are related to each other. A Block object contains +// 0 or more Relation objects in a list, Relationships . For more information, see Block +// . +// +// The Type element provides the type of the relationship for all blocks in the IDs +// array. +type Relationship struct { + + // An array of IDs for related blocks. You can get the type of the relationship + // from the Type element. + Ids []string + + // The type of relationship between the blocks in the IDs array and the current + // block. The following list describes the relationship types that can be returned. + // + // - VALUE - A list that contains the ID of the VALUE block that's associated + // with the KEY of a key-value pair. + // + // - CHILD - A list of IDs that identify blocks found within the current block + // object. For example, WORD blocks have a CHILD relationship to the LINE block + // type. + // + // - MERGED_CELL - A list of IDs that identify each of the MERGED_CELL block + // types in a table. + // + // - ANSWER - A list that contains the ID of the QUERY_RESULT block that’s + // associated with the corresponding QUERY block. + // + // - TABLE - A list of IDs that identify associated TABLE block types. + // + // - TABLE_TITLE - A list that contains the ID for the TABLE_TITLE block type in + // a table. + // + // - TABLE_FOOTER - A list of IDs that identify the TABLE_FOOTER block types in + // a table. + Type RelationshipType + + noSmithyDocumentSerde +} + +// The S3 bucket name and file name that identifies the document. +// +// The AWS Region for the S3 bucket that contains the document must match the +// Region that you use for Amazon Textract operations. +// +// For Amazon Textract to process a file in an S3 bucket, the user must have +// permission to access the S3 bucket and file. +type S3Object struct { + + // The name of the S3 bucket. Note that the # character is not valid in the file + // name. + Bucket *string + + // The file name of the input document. Synchronous operations can use image files + // that are in JPEG or PNG format. Asynchronous operations also support PDF and + // TIFF format files. + Name *string + + // If the bucket has versioning enabled, you can specify the object version. + Version *string + + noSmithyDocumentSerde +} + +// Information regarding a detected signature on a page. +type SignatureDetection struct { + + // The confidence, from 0 to 100, in the predicted values for a detected signature. + Confidence *float32 + + // Information about where the following items are located on a document page: + // detected page, text, key-value pairs, tables, table cells, and selection + // elements. + Geometry *Geometry + + noSmithyDocumentSerde +} + +// Contains information about the pages of a document, defined by logical boundary. +type SplitDocument struct { + + // The index for a given document in a DocumentGroup of a specific Type. + Index *int32 + + // An array of page numbers for a for a given document, ordered by logical + // boundary. + Pages []int32 + + noSmithyDocumentSerde +} + +// A structure containing information about an undetected signature on a page +// where it was expected but not found. +type UndetectedSignature struct { + + // The page where a signature was expected but not found. + Page *int32 + + noSmithyDocumentSerde +} + +// A warning about an issue that occurred during asynchronous text analysis (StartDocumentAnalysis ) or +// asynchronous document text detection (StartDocumentTextDetection ). +type Warning struct { + + // The error code for the warning. + ErrorCode *string + + // A list of the pages that the warning applies to. + Pages []int32 + + noSmithyDocumentSerde +} + +type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/textract/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/validators.go new file mode 100644 index 00000000..0e67ffcb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/textract/validators.go @@ -0,0 +1,1160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package textract + +import ( + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/textract/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/middleware" +) + +type validateOpAnalyzeDocument struct { +} + +func (*validateOpAnalyzeDocument) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAnalyzeDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AnalyzeDocumentInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAnalyzeDocumentInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAnalyzeExpense struct { +} + +func (*validateOpAnalyzeExpense) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAnalyzeExpense) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AnalyzeExpenseInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAnalyzeExpenseInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAnalyzeID struct { +} + +func (*validateOpAnalyzeID) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAnalyzeID) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AnalyzeIDInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAnalyzeIDInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateAdapter struct { +} + +func (*validateOpCreateAdapter) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateAdapter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateAdapterInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateAdapterInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateAdapterVersion struct { +} + +func (*validateOpCreateAdapterVersion) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateAdapterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateAdapterVersionInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateAdapterVersionInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteAdapter struct { +} + +func (*validateOpDeleteAdapter) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteAdapter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteAdapterInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteAdapterInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteAdapterVersion struct { +} + +func (*validateOpDeleteAdapterVersion) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteAdapterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteAdapterVersionInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteAdapterVersionInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDetectDocumentText struct { +} + +func (*validateOpDetectDocumentText) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDetectDocumentText) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DetectDocumentTextInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDetectDocumentTextInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetAdapter struct { +} + +func (*validateOpGetAdapter) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetAdapter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetAdapterInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetAdapterInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetAdapterVersion struct { +} + +func (*validateOpGetAdapterVersion) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetAdapterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetAdapterVersionInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetAdapterVersionInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetDocumentAnalysis struct { +} + +func (*validateOpGetDocumentAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetDocumentAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetDocumentAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetDocumentAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetDocumentTextDetection struct { +} + +func (*validateOpGetDocumentTextDetection) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetDocumentTextDetection) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetDocumentTextDetectionInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetDocumentTextDetectionInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetExpenseAnalysis struct { +} + +func (*validateOpGetExpenseAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetExpenseAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetExpenseAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetExpenseAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetLendingAnalysis struct { +} + +func (*validateOpGetLendingAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetLendingAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetLendingAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetLendingAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetLendingAnalysisSummary struct { +} + +func (*validateOpGetLendingAnalysisSummary) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetLendingAnalysisSummary) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetLendingAnalysisSummaryInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetLendingAnalysisSummaryInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListTagsForResource struct { +} + +func (*validateOpListTagsForResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListTagsForResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListTagsForResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListTagsForResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartDocumentAnalysis struct { +} + +func (*validateOpStartDocumentAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartDocumentAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartDocumentAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartDocumentAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartDocumentTextDetection struct { +} + +func (*validateOpStartDocumentTextDetection) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartDocumentTextDetection) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartDocumentTextDetectionInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartDocumentTextDetectionInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartExpenseAnalysis struct { +} + +func (*validateOpStartExpenseAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartExpenseAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartExpenseAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartExpenseAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartLendingAnalysis struct { +} + +func (*validateOpStartLendingAnalysis) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartLendingAnalysis) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartLendingAnalysisInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartLendingAnalysisInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpTagResource struct { +} + +func (*validateOpTagResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpTagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*TagResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpTagResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUntagResource struct { +} + +func (*validateOpUntagResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUntagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UntagResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUntagResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateAdapter struct { +} + +func (*validateOpUpdateAdapter) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateAdapter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateAdapterInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateAdapterInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +func addOpAnalyzeDocumentValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAnalyzeDocument{}, middleware.After) +} + +func addOpAnalyzeExpenseValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAnalyzeExpense{}, middleware.After) +} + +func addOpAnalyzeIDValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAnalyzeID{}, middleware.After) +} + +func addOpCreateAdapterValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateAdapter{}, middleware.After) +} + +func addOpCreateAdapterVersionValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateAdapterVersion{}, middleware.After) +} + +func addOpDeleteAdapterValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteAdapter{}, middleware.After) +} + +func addOpDeleteAdapterVersionValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteAdapterVersion{}, middleware.After) +} + +func addOpDetectDocumentTextValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDetectDocumentText{}, middleware.After) +} + +func addOpGetAdapterValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetAdapter{}, middleware.After) +} + +func addOpGetAdapterVersionValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetAdapterVersion{}, middleware.After) +} + +func addOpGetDocumentAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetDocumentAnalysis{}, middleware.After) +} + +func addOpGetDocumentTextDetectionValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetDocumentTextDetection{}, middleware.After) +} + +func addOpGetExpenseAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetExpenseAnalysis{}, middleware.After) +} + +func addOpGetLendingAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetLendingAnalysis{}, middleware.After) +} + +func addOpGetLendingAnalysisSummaryValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetLendingAnalysisSummary{}, middleware.After) +} + +func addOpListTagsForResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListTagsForResource{}, middleware.After) +} + +func addOpStartDocumentAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartDocumentAnalysis{}, middleware.After) +} + +func addOpStartDocumentTextDetectionValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartDocumentTextDetection{}, middleware.After) +} + +func addOpStartExpenseAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartExpenseAnalysis{}, middleware.After) +} + +func addOpStartLendingAnalysisValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartLendingAnalysis{}, middleware.After) +} + +func addOpTagResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpTagResource{}, middleware.After) +} + +func addOpUntagResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUntagResource{}, middleware.After) +} + +func addOpUpdateAdapterValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateAdapter{}, middleware.After) +} + +func validateAdapter(v *types.Adapter) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "Adapter"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if v.Version == nil { + invalidParams.Add(smithy.NewErrParamRequired("Version")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAdapters(v []types.Adapter) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "Adapters"} + for i := range v { + if err := validateAdapter(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAdaptersConfig(v *types.AdaptersConfig) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdaptersConfig"} + if v.Adapters == nil { + invalidParams.Add(smithy.NewErrParamRequired("Adapters")) + } else if v.Adapters != nil { + if err := validateAdapters(v.Adapters); err != nil { + invalidParams.AddNested("Adapters", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateHumanLoopConfig(v *types.HumanLoopConfig) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "HumanLoopConfig"} + if v.HumanLoopName == nil { + invalidParams.Add(smithy.NewErrParamRequired("HumanLoopName")) + } + if v.FlowDefinitionArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("FlowDefinitionArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateNotificationChannel(v *types.NotificationChannel) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "NotificationChannel"} + if v.SNSTopicArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("SNSTopicArn")) + } + if v.RoleArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOutputConfig(v *types.OutputConfig) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "OutputConfig"} + if v.S3Bucket == nil { + invalidParams.Add(smithy.NewErrParamRequired("S3Bucket")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateQueries(v []types.Query) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "Queries"} + for i := range v { + if err := validateQuery(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateQueriesConfig(v *types.QueriesConfig) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "QueriesConfig"} + if v.Queries == nil { + invalidParams.Add(smithy.NewErrParamRequired("Queries")) + } else if v.Queries != nil { + if err := validateQueries(v.Queries); err != nil { + invalidParams.AddNested("Queries", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateQuery(v *types.Query) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "Query"} + if v.Text == nil { + invalidParams.Add(smithy.NewErrParamRequired("Text")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAnalyzeDocumentInput(v *AnalyzeDocumentInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AnalyzeDocumentInput"} + if v.Document == nil { + invalidParams.Add(smithy.NewErrParamRequired("Document")) + } + if v.FeatureTypes == nil { + invalidParams.Add(smithy.NewErrParamRequired("FeatureTypes")) + } + if v.HumanLoopConfig != nil { + if err := validateHumanLoopConfig(v.HumanLoopConfig); err != nil { + invalidParams.AddNested("HumanLoopConfig", err.(smithy.InvalidParamsError)) + } + } + if v.QueriesConfig != nil { + if err := validateQueriesConfig(v.QueriesConfig); err != nil { + invalidParams.AddNested("QueriesConfig", err.(smithy.InvalidParamsError)) + } + } + if v.AdaptersConfig != nil { + if err := validateAdaptersConfig(v.AdaptersConfig); err != nil { + invalidParams.AddNested("AdaptersConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAnalyzeExpenseInput(v *AnalyzeExpenseInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AnalyzeExpenseInput"} + if v.Document == nil { + invalidParams.Add(smithy.NewErrParamRequired("Document")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAnalyzeIDInput(v *AnalyzeIDInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AnalyzeIDInput"} + if v.DocumentPages == nil { + invalidParams.Add(smithy.NewErrParamRequired("DocumentPages")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateAdapterInput(v *CreateAdapterInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateAdapterInput"} + if v.AdapterName == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterName")) + } + if v.FeatureTypes == nil { + invalidParams.Add(smithy.NewErrParamRequired("FeatureTypes")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateAdapterVersionInput(v *CreateAdapterVersionInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateAdapterVersionInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if v.DatasetConfig == nil { + invalidParams.Add(smithy.NewErrParamRequired("DatasetConfig")) + } + if v.OutputConfig == nil { + invalidParams.Add(smithy.NewErrParamRequired("OutputConfig")) + } else if v.OutputConfig != nil { + if err := validateOutputConfig(v.OutputConfig); err != nil { + invalidParams.AddNested("OutputConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteAdapterInput(v *DeleteAdapterInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteAdapterInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteAdapterVersionInput(v *DeleteAdapterVersionInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteAdapterVersionInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if v.AdapterVersion == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterVersion")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDetectDocumentTextInput(v *DetectDocumentTextInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DetectDocumentTextInput"} + if v.Document == nil { + invalidParams.Add(smithy.NewErrParamRequired("Document")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetAdapterInput(v *GetAdapterInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetAdapterInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetAdapterVersionInput(v *GetAdapterVersionInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetAdapterVersionInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if v.AdapterVersion == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterVersion")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetDocumentAnalysisInput(v *GetDocumentAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetDocumentAnalysisInput"} + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetDocumentTextDetectionInput(v *GetDocumentTextDetectionInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetDocumentTextDetectionInput"} + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetExpenseAnalysisInput(v *GetExpenseAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetExpenseAnalysisInput"} + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetLendingAnalysisInput(v *GetLendingAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetLendingAnalysisInput"} + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetLendingAnalysisSummaryInput(v *GetLendingAnalysisSummaryInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetLendingAnalysisSummaryInput"} + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListTagsForResourceInput(v *ListTagsForResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListTagsForResourceInput"} + if v.ResourceARN == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceARN")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartDocumentAnalysisInput(v *StartDocumentAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartDocumentAnalysisInput"} + if v.DocumentLocation == nil { + invalidParams.Add(smithy.NewErrParamRequired("DocumentLocation")) + } + if v.FeatureTypes == nil { + invalidParams.Add(smithy.NewErrParamRequired("FeatureTypes")) + } + if v.NotificationChannel != nil { + if err := validateNotificationChannel(v.NotificationChannel); err != nil { + invalidParams.AddNested("NotificationChannel", err.(smithy.InvalidParamsError)) + } + } + if v.OutputConfig != nil { + if err := validateOutputConfig(v.OutputConfig); err != nil { + invalidParams.AddNested("OutputConfig", err.(smithy.InvalidParamsError)) + } + } + if v.QueriesConfig != nil { + if err := validateQueriesConfig(v.QueriesConfig); err != nil { + invalidParams.AddNested("QueriesConfig", err.(smithy.InvalidParamsError)) + } + } + if v.AdaptersConfig != nil { + if err := validateAdaptersConfig(v.AdaptersConfig); err != nil { + invalidParams.AddNested("AdaptersConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartDocumentTextDetectionInput(v *StartDocumentTextDetectionInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartDocumentTextDetectionInput"} + if v.DocumentLocation == nil { + invalidParams.Add(smithy.NewErrParamRequired("DocumentLocation")) + } + if v.NotificationChannel != nil { + if err := validateNotificationChannel(v.NotificationChannel); err != nil { + invalidParams.AddNested("NotificationChannel", err.(smithy.InvalidParamsError)) + } + } + if v.OutputConfig != nil { + if err := validateOutputConfig(v.OutputConfig); err != nil { + invalidParams.AddNested("OutputConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartExpenseAnalysisInput(v *StartExpenseAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartExpenseAnalysisInput"} + if v.DocumentLocation == nil { + invalidParams.Add(smithy.NewErrParamRequired("DocumentLocation")) + } + if v.NotificationChannel != nil { + if err := validateNotificationChannel(v.NotificationChannel); err != nil { + invalidParams.AddNested("NotificationChannel", err.(smithy.InvalidParamsError)) + } + } + if v.OutputConfig != nil { + if err := validateOutputConfig(v.OutputConfig); err != nil { + invalidParams.AddNested("OutputConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartLendingAnalysisInput(v *StartLendingAnalysisInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartLendingAnalysisInput"} + if v.DocumentLocation == nil { + invalidParams.Add(smithy.NewErrParamRequired("DocumentLocation")) + } + if v.NotificationChannel != nil { + if err := validateNotificationChannel(v.NotificationChannel); err != nil { + invalidParams.AddNested("NotificationChannel", err.(smithy.InvalidParamsError)) + } + } + if v.OutputConfig != nil { + if err := validateOutputConfig(v.OutputConfig); err != nil { + invalidParams.AddNested("OutputConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpTagResourceInput(v *TagResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "TagResourceInput"} + if v.ResourceARN == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceARN")) + } + if v.Tags == nil { + invalidParams.Add(smithy.NewErrParamRequired("Tags")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUntagResourceInput(v *UntagResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UntagResourceInput"} + if v.ResourceARN == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceARN")) + } + if v.TagKeys == nil { + invalidParams.Add(smithy.NewErrParamRequired("TagKeys")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateAdapterInput(v *UpdateAdapterInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateAdapterInput"} + if v.AdapterId == nil { + invalidParams.Add(smithy.NewErrParamRequired("AdapterId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 38912c49..9f878387 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -122,6 +122,11 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc/types github.com/aws/aws-sdk-go-v2/service/sts github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sts/types +# github.com/aws/aws-sdk-go-v2/service/textract v1.35.1 +## explicit; go 1.22 +github.com/aws/aws-sdk-go-v2/service/textract +github.com/aws/aws-sdk-go-v2/service/textract/internal/endpoints +github.com/aws/aws-sdk-go-v2/service/textract/types # github.com/aws/smithy-go v1.22.3 ## explicit; go 1.22 github.com/aws/smithy-go