translate

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Translate

Parity grade: A · SDK aws-sdk-go-v2/service/translate@v1.36.4 · last audited 2026-08-20 (1efb1a758)

Coverage

Metric Value
PARITY entries audited 19 (19 ok)
Feature families 5 (5 ok)
Known gaps 7
Deferred items 0
Resource leaks clean
Known gaps
  • IMPOSSIBLE (re-confirmed gopherstack-llun): TranslateText/TranslateDocument echo SourceLanguageCode literally as 'auto' when omitted, instead of resolving it to a detected language code the way real AWS does (via an internal Comprehend call). Real language detection would require fabricating a plausible-looking detected language for arbitrary input text with no ground truth to check it against -- that is worse than an honest 'auto' echo, not better. Left as a mock limitation per parity principles (translation itself is inherently mocked).
  • ALREADY COVERED BY CHAOS (verified gopherstack-llun; CORRECTED 2026-09-04 for UpdateParallelData, see its ops entry): DetectedLanguageLowConfidenceException, TooManyRequestsException, InternalServerException, and ServiceUnavailableException (plus ConcurrentModificationException for every op EXCEPT UpdateParallelData) are real modeled errors for several ops but have no deterministic backend-state trigger in this synchronous, single-lock, unbounded in-memory emulator (no rate limiting, no enforced per-account resource quotas, no real concurrent-write races, no real Comprehend-backed language detection). Concretely verified this pass: translate.Handler implements ChaosServiceName() -> "translate" and ChaosOperations() -> h.GetSupportedOperations() (handler.go), and pkgs/chaos.Middleware is wired globally via registry.Use(chaos.Middleware(faultStore)) in cli.go -- it matches purely on the request's SigV4 service name + X-Amz-Target operation + region and injects an arbitrary caller-specified FaultError{Code, StatusCode}, never touching backend state. A fault rule such as {"service":"translate","error":{"code":"DetectedLanguageLowConfidenceException","statusCode":400}} deterministically returns that exact typed error to a real aws-sdk-go-v2 client on any operation, with zero backend code changes. Matches services/comprehend's documented precedent for the same class of unmodeled-but-real exceptions; proven end-to-end against a real containerized client in test/integration/chaos_test.go. DeleteParallelData also models ConcurrentModificationException with the same 'modification in progress' semantics, but no doc sentence on DeleteParallelData itself confirms delete is blocked during CREATING/UPDATING the way UpdateParallelData's fix does -- left ungated per the no-invented-guards rule; flagging for a future pass with stronger evidence.
  • IMPOSSIBLE (re-confirmed gopherstack-llun): EncryptionKey.Type (KMS-only enum) and EncryptionKey.Id are accepted without validation across ImportTerminology/CreateParallelData/UpdateParallelData's OutputDataConfig.EncryptionKey. Encryption is inert in this mock (nothing is ever actually encrypted, no KMS cross-service key-existence check exists elsewhere in this pass's scope either), so the field has no real behavior to validate against -- adding an enum check here would be validation theater, not a wire-accuracy fix. Low-value/low-risk gap, left as-is.
  • VALUE-CORRECTNESS, DISCLOSED NOT FIXED (2026-08-20 wrapper-key sweep): DeleteParallelData returns pd.Status as it stood immediately before deletion (e.g. ACTIVE), never the DELETING value real AWS documents for 'the status of the parallel data deletion' (DeleteParallelDataResponse.Status, botocore service-2.json). This is a right-key/right-type/questionable-VALUE issue, not a shape break -- ACTIVE is still a valid ParallelDataStatus enum member, so no client-side deserialization failure results -- and fixing it properly would need a transient DELETING state in the lifecycle model (delete marks DELETING, a later poll/janitor actually removes the row), which is lifecycle-state-machine work out of scope for a wrapper-key/nesting sweep. Left as-is; flagging for a future targeted pass.
  • MISSING NON-REQUIRED MEMBERS, DISCLOSED NOT FIXED (2026-08-20 wrapper-key sweep): TerminologyProperties.SkippedTermCount and .Message, and ParallelDataProperties.FailedRecordCount/ImportedDataSize/ImportedRecordCount/SkippedRecordCount/.Message are real optional response members this emulator never populates (terminologyToMap/parallelDataToMap omit them entirely rather than emitting a zero value). None are marked required in types.TerminologyProperties/types.ParallelDataProperties, and populating them honestly would require modeling per-record import/skip counters the backend doesn't track today -- Layer-3-scope, left as a disclosed gap rather than fabricated.
  • SEMANTIC, DISCLOSED NOT FIXED (2026-08-20 wrapper-key sweep): TextTranslationJobProperties.JobDetails is always {TranslatedDocumentsCount:0, DocumentsWithErrorsCount:0, InputDocumentsCount:0} regardless of job size (jobToMap, handler_text_translation_jobs.go) -- the wrapper key and nested field names are correct (verified against types.JobDetails), but the values are a hardcoded stub since this emulator never actually reads/counts documents in the InputDataConfig S3 location. Semantic gap, not a wire-shape bug; left as-is.
  • SEMANTIC, DISCLOSED NOT FIXED (gopherstack-wksw, 2026-08-29 constraint-not-honoured sweep): ListLanguages' DisplayLanguageCode is validated against the real 10-value enum (fixed by a prior pass, see ops entry) but never actually applied -- knownLanguages() (handler_languages.go) returns every LanguageName in English regardless of the requested DisplayLanguageCode, since this emulator has no localized name table for the ~75 x 10 language/display-language combinations real AWS serves. The response's own DisplayLanguageCode field correctly echoes what was requested, so a client can tell what it asked for; only the LanguageName strings themselves don't follow it. Structural gap (no i18n data modeled anywhere in this service), not a filter/pagination bug -- left as-is rather than fabricating partial translations for a handful of languages.

More

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a requested resource is absent. Also used
	// (per the real per-operation error models) for operations whose only
	// modeled client-error exception IS ResourceNotFoundException -- i.e.
	// GetParallelData/DeleteParallelData/StopTextTranslationJob/
	// DescribeTextTranslationJob have no InvalidRequestException or
	// InvalidParameterValueException in their error list at all, so an
	// empty/missing key on those operations must still surface as
	// ResourceNotFoundException, not a validation exception the real
	// operation never throws.
	ErrNotFound = errors.New("ResourceNotFoundException")
	// ErrConflict is returned when a named resource already exists (name
	// conflict on CreateParallelData). Real Amazon Translate has no
	// "ResourceInUseException" shape at all (confirmed: absent from
	// types/errors.go and the smithy model) -- CreateParallelData models
	// ConflictException for exactly this case.
	ErrConflict = errors.New("ConflictException")
	// ErrValidation is returned for invalid/missing request values on
	// operations whose modeled error list includes InvalidRequestException:
	// CreateParallelData, UpdateParallelData, StartTextTranslationJob,
	// ListTextTranslationJobs, TranslateText, TranslateDocument.
	ErrValidation = errors.New("InvalidRequestException")
	// ErrInvalidParameter is returned for invalid/missing request values on
	// operations whose modeled error list includes
	// InvalidParameterValueException but NOT InvalidRequestException:
	// ImportTerminology, GetTerminology, DeleteTerminology,
	// ListTerminologies, GetParallelData, ListParallelData, TagResource,
	// UntagResource, ListTagsForResource, ListLanguages.
	ErrInvalidParameter = errors.New("InvalidParameterValueException")
	// ErrLimitExceeded is returned when a request would exceed a modeled
	// service quota: the 10 MB custom terminology file size limit
	// (ImportTerminology) or the 100,000-byte TranslateDocument document
	// size limit (TranslateDocument), both confirmed against the
	// TerminologyFile/DocumentContent blob shapes' "max" constraints in the
	// smithy model.
	ErrLimitExceeded = errors.New("LimitExceededException")
	// ErrTextSizeLimitExceeded is returned when TranslateText's Text exceeds
	// the 10,000-byte synchronous translation quota (confirmed against
	// BoundedLengthString's "max": 10000 in the smithy model and the Amazon
	// Translate guidelines/quotas page).
	ErrTextSizeLimitExceeded = errors.New("TextSizeLimitExceededException")
	// ErrTooManyTags is returned when a resource would carry more than the
	// 50-tag-per-resource limit (both existing and newly requested tags
	// count), matching TooManyTagsException.
	ErrTooManyTags = errors.New("TooManyTagsException")
	// ErrUnsupportedLanguagePair is returned when TranslateText,
	// TranslateDocument, or StartTextTranslationJob is given a
	// SourceLanguageCode (other than "auto") or target language code not in
	// Translate's supported language list (see handler_languages.go's
	// knownLanguages, the same list ListLanguages serves).
	ErrUnsupportedLanguagePair = errors.New("UnsupportedLanguagePairException")
	// ErrUnsupportedDisplayLanguage is returned when ListLanguages is given
	// a DisplayLanguageCode outside the fixed 10-value enum Translate
	// actually supports for UI localization (de/en/es/fr/it/ja/ko/pt/zh/
	// zh-TW -- confirmed against the DisplayLanguageCode shape's "enum" in
	// the smithy model; this is a much smaller set than the ~75
	// translation-target language codes).
	ErrUnsupportedDisplayLanguage = errors.New("UnsupportedDisplayLanguageCodeException")
	// ErrInvalidFilter is returned when ListTextTranslationJobs is given a
	// Filter.JobStatus value outside the modeled JobStatus enum.
	ErrInvalidFilter = errors.New("InvalidFilterException")
	// ErrConcurrentModification is returned when UpdateParallelData targets a
	// parallel data resource that is still CREATING or UPDATING from a prior
	// call. types/errors.go's ConcurrentModificationException doc: "Another
	// modification is being made. That modification must complete before you
	// can make your change." UpdateParallelData models this exception
	// (deserializers.go's awsAwsjson11_deserializeOpErrorUpdateParallelData).
	ErrConcurrentModification = errors.New("ConcurrentModificationException")
)

Sentinel errors map 1:1 to Translate's modeled exception shapes (aws-sdk-go-v2/service/translate/types/errors.go, confirmed against the smithy model's per-operation error lists in aws-sdk-go@v1.55.5/models/apis/translate/2017-07-01/api-2.json). handleError in handler.go matches each with errors.Is and emits the exact "__type" wire code; every exception below is smithy.FaultClient (HTTP 400) per the real SDK's ErrorFault() implementations and the AWS API reference's documented "HTTP Status Code: 400" for each -- only InternalServerException and ServiceUnavailableException are FaultServer (500), and neither has a deterministic trigger in this synchronous, single-lock, unbounded in-memory emulator (no internal faults, no real service outages) any more than TooManyRequestsException (no rate limiting) or DetectedLanguageLowConfidenceException (no real Comprehend-backed detection). Generic throttling/5xx injection for any operation is available instead through the chaos fault-injection system (ChaosOperations/ChaosServiceName), matching services/comprehend's documented precedent for the same class of unmodeled-but-real exceptions. ConcurrentModificationException is the one exception in that "no deterministic trigger" family that turned out to have one: this emulator's own CREATING/UPDATING -> ACTIVE async lifecycle (parallel_data.go) is a real, observable non-terminal window, not a genuine goroutine race -- see ErrConcurrentModification below.

View Source
var ErrNilAppContext = errors.New("AppContext is required")

ErrNilAppContext is returned when Provider.Init is called with a nil AppContext.

Functions

This section is empty.

Types

type EncryptionKey

type EncryptionKey struct {
	Type string
	ID   string
}

EncryptionKey holds optional KMS encryption key details.

type Handler

type Handler struct {
	Backend *InMemoryBackend
	// contains filtered or unexported fields
}

Handler serves Amazon Translate JSON operations.

func NewHandler

func NewHandler(backend *InMemoryBackend) *Handler

NewHandler creates a Translate handler backed by in-memory state.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns fault-injectable operations.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns configured service region.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns service key for fault matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation returns the operation name from the request target.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource retrieves the primary resource name.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns all implemented operation names.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo HTTP handler.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns header matching priority.

func (*Handler) Name

func (h *Handler) Name() string

Name returns service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears backend state.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher matches Translate X-Amz-Target headers.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend. Handler previously had no Snapshot/Restore of its own -- and neither did InMemoryBackend -- so cli.go's generic setupPersistence (which type-asserts the registered service.Registerable, i.e. the Handler, for a Snapshot/Restore pair) never picked Translate up at all: dead wiring, with no persistence underneath it either. This delegation (matching the codecommit/polly/cleanrooms pattern) is what wires Translate into persistence for the first time.

type InMemoryBackend

type InMemoryBackend struct {
	// contains filtered or unexported fields
}

InMemoryBackend stores Translate state for concurrent requests.

terminologies, parallelData, and jobs are *store.Table[T]-backed (see store_setup.go and pkgs/store's package doc); tags remains a plain map since its values are map[string]string, not *T, so there is nothing for store.Table to key on.

func NewInMemoryBackend

func NewInMemoryBackend(accountID, region string) *InMemoryBackend

NewInMemoryBackend returns an initialized InMemoryBackend.

func (*InMemoryBackend) AccountID

func (b *InMemoryBackend) AccountID() string

AccountID returns the configured account ID.

func (*InMemoryBackend) CreateParallelData

func (b *InMemoryBackend) CreateParallelData(
	name, description string,
	cfg *ParallelDataConfig,
	encKey *EncryptionKey,
	tags map[string]string,
) (*ParallelData, error)

CreateParallelData creates a new parallel data resource.

func (*InMemoryBackend) DeleteParallelData

func (b *InMemoryBackend) DeleteParallelData(name string) (*ParallelData, error)

DeleteParallelData removes a parallel data resource by name.

func (*InMemoryBackend) DeleteTerminology

func (b *InMemoryBackend) DeleteTerminology(name string) error

DeleteTerminology removes a terminology by name.

func (*InMemoryBackend) DescribeTextTranslationJob

func (b *InMemoryBackend) DescribeTextTranslationJob(jobID string) (*TranslationJob, error)

DescribeTextTranslationJob retrieves a translation job and advances it one step through its lifecycle, matching services/comprehend's DescribeJob pattern: real batch translation jobs move from SUBMITTED to IN_PROGRESS to a terminal state (COMPLETED/FAILED, or STOPPED once stop was requested) asynchronously. Without this, a job started via StartTextTranslationJob would sit at its initial status forever and SDK callers polling DescribeTextTranslationJob (the documented way to track job progress) would never observe completion.

func (*InMemoryBackend) GetParallelData

func (b *InMemoryBackend) GetParallelData(name string) (*ParallelData, error)

GetParallelData retrieves a parallel data resource by name and advances it one step through its async CREATING/UPDATING -> ACTIVE lifecycle. This takes the write lock (not RLock) because advanceParallelData mutates state, matching DescribeTextTranslationJob's documented precedent in text_translation_jobs.go.

func (*InMemoryBackend) GetTerminology

func (b *InMemoryBackend) GetTerminology(name string) (*Terminology, error)

GetTerminology retrieves a terminology by name.

func (*InMemoryBackend) ImportTerminology

func (b *InMemoryBackend) ImportTerminology(
	name, description string,
	data *TerminologyData,
	encKey *EncryptionKey,
	tags map[string]string,
) (*Terminology, error)

ImportTerminology creates or overwrites a custom terminology.

func (*InMemoryBackend) ListParallelData

func (b *InMemoryBackend) ListParallelData(maxResults int, nextToken string) ([]*ParallelData, string)

ListParallelData returns a paginated list of parallel data resources.

func (*InMemoryBackend) ListTagsForResource

func (b *InMemoryBackend) ListTagsForResource(resourceARN string) (map[string]string, error)

ListTagsForResource returns tags for a resource.

func (*InMemoryBackend) ListTerminologies

func (b *InMemoryBackend) ListTerminologies(maxResults int, nextToken string) ([]*Terminology, string)

ListTerminologies returns a paginated list of terminologies.

func (*InMemoryBackend) ListTextTranslationJobs

func (b *InMemoryBackend) ListTextTranslationJobs(
	filter TextTranslationJobFilter,
	maxResults int,
	nextToken string,
) ([]*TranslationJob, string)

ListTextTranslationJobs returns a paginated list of translation jobs.

func (*InMemoryBackend) LookupTerminologies

func (b *InMemoryBackend) LookupTerminologies(names []string) ([]*Terminology, error)

LookupTerminologies returns terminology entries for the given names. A name that does not correspond to any stored terminology is a ResourceNotFoundException (TranslateText/TranslateDocument both model this exception, and TerminologyNames is the only named-resource reference either operation makes -- real AWS's ListTerminologies doc note "Use the ListTerminologies operation to get the available terminology lists" implies the reference is validated, not silently ignored).

func (*InMemoryBackend) Region

func (b *InMemoryBackend) Region() string

Region returns the configured region.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all stored state.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore deserializes backend state from a snapshot. It implements persistence.Persistable.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serializes the backend state to JSON. It implements persistence.Persistable.

func (*InMemoryBackend) StartTextTranslationJob

func (b *InMemoryBackend) StartTextTranslationJob(
	jobName, dataAccessRoleARN, sourceLang string,
	targetLangs, terminologyNames, parallelDataNames []string,
	inputCfg, outputCfg, settings map[string]any,
	tags map[string]string,
) (*TranslationJob, error)

StartTextTranslationJob creates a new async translation job.

func (*InMemoryBackend) StopTextTranslationJob

func (b *InMemoryBackend) StopTextTranslationJob(jobID string) (*TranslationJob, error)

StopTextTranslationJob requests stop of a translation job.

func (*InMemoryBackend) TagResource

func (b *InMemoryBackend) TagResource(resourceARN string, newTags map[string]string) error

TagResource adds or replaces tags on a resource.

func (*InMemoryBackend) TaggedResources added in v1.3.1

func (b *InMemoryBackend) TaggedResources() []TaggedEntry

TaggedResources returns every terminology and parallel data ARN that currently has at least one tag applied via TagResource.

func (*InMemoryBackend) UntagResource

func (b *InMemoryBackend) UntagResource(resourceARN string, keys []string) error

UntagResource removes specific tags from a resource.

func (*InMemoryBackend) UpdateParallelData

func (b *InMemoryBackend) UpdateParallelData(
	name, description string,
	cfg *ParallelDataConfig,
) (*ParallelData, error)

UpdateParallelData updates an existing parallel data resource. Real AWS puts the resource into UPDATING (and records a new LatestUpdateAttemptStatus/LatestUpdateAttemptAt attempt) until the update completes asynchronously; GetParallelData's advanceParallelData call carries it to ACTIVE, matching CreateParallelData's CREATING -> ACTIVE lifecycle above.

type ParallelData

type ParallelData struct {
	ParallelDataConfig *ParallelDataConfig
	EncryptionKey      *EncryptionKey
	Tags               map[string]string
	CreatedAt          time.Time
	LastUpdatedAt      time.Time
	// LatestUpdateAttemptAt is the zero time until UpdateParallelData is
	// called at least once.
	LatestUpdateAttemptAt time.Time
	ARN                   string
	Name                  string
	Description           string
	SourceLanguage        string
	Status                string
	// LatestUpdateAttemptStatus tracks the outcome of the most recent
	// UpdateParallelData call (real ParallelDataProperties/
	// UpdateParallelDataOutput field), empty until the first update.
	LatestUpdateAttemptStatus string
	TargetLanguages           []string
}

ParallelData stores a parallel data resource.

type ParallelDataConfig

type ParallelDataConfig struct {
	S3URI  string
	Format string
}

ParallelDataConfig holds S3 data config for parallel data.

type Provider

type Provider struct{}

Provider implements service.Provider for the Translate service.

func (*Provider) Init

Init initializes the Translate backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the logical name of the provider.

type TaggedEntry added in v1.3.1

type TaggedEntry struct {
	Tags map[string]string
	ARN  string
}

TaggedEntry pairs a resource ARN with its tags.

type Terminology

type Terminology struct {
	TerminologyData *TerminologyData
	EncryptionKey   *EncryptionKey
	Tags            map[string]string
	CreatedAt       time.Time
	LastUpdatedAt   time.Time
	ARN             string
	Name            string
	Description     string
	SourceLanguage  string
	Directionality  string
	Format          string
	TargetLanguages []string
	SizeBytes       int
	TermCount       int
}

Terminology stores a custom terminology resource.

type TerminologyData

type TerminologyData struct {
	Format         string
	Directionality string
	File           []byte
}

TerminologyData holds imported terminology file bytes.

type TextTranslationJobFilter

type TextTranslationJobFilter struct {
	SubmittedAfterTime  *time.Time
	SubmittedBeforeTime *time.Time
	JobName             string
	JobStatus           string
}

TextTranslationJobFilter mirrors types.TextTranslationJobFilter (api_op_ListTextTranslationJobs.go): JobName/JobStatus/SubmittedAfterTime/ SubmittedBeforeTime, each optional and independently zero-valued when unset.

type TranslationJob

type TranslationJob struct {
	InputDataConfig   map[string]any
	OutputDataConfig  map[string]any
	Settings          map[string]any
	Tags              map[string]string
	SubmittedAt       time.Time
	EndAt             time.Time
	JobID             string
	JobName           string
	JobStatus         string
	DataAccessRoleARN string
	SourceLanguage    string
	Message           string
	TargetLanguages   []string
	TerminologyNames  []string
	ParallelDataNames []string
	// contains filtered or unexported fields
}

TranslationJob stores an async translation job.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL