Debian Codegraph @

samples/order/processor.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // A processor processes images in orders. It receives requests by
16 // subscribing to the requests topic, and writes responses to the response
17 // topic.
18 //
19 // At present, it just encodes input images into PNG format.
20
21 package main
22
23 import (
24 "context"
25 "encoding/json"
26 "fmt"
27 "image"
28 _ "image/jpeg"
29 "image/png"
30 "log"
31 "math/rand"
32 "strings"
33 "time"
34
35 "gocloud.dev/blob"
36 _ "gocloud.dev/blob/fileblob"
37 "gocloud.dev/docstore"
38 _ "gocloud.dev/docstore/memdocstore"
39 "gocloud.dev/gcerrors"
40 "gocloud.dev/pubsub"
41 _ "gocloud.dev/pubsub/mempubsub"
42 )
43
44 // A processor holds the state for processing images.
45 type processor struct {
46 requestSub *pubsub.Subscription
47 bucket *blob.Bucket
48 coll *docstore.Collection
49 }
50
51 // run handles requests until the context is done or there is a fatal error.
52 func (p *processor) run(ctx context.Context) error {
53 for {
54 if err := p.handleRequest(ctx); err != nil {
55 return err
56 }
57 }
58 }
59
60 // handleRequest handles one image-processing request.
61 // A non-nil error from handleRequest will end request processing.
62 func (p *processor) handleRequest(ctx context.Context) error {
63 msg, err := p.requestSub.Receive(ctx)
64 if err != nil {
65 // If we can't receive messages, we should stop processing.
66 return err
67 }
68
69 var req OrderRequest
70 if err := json.Unmarshal(msg.Body, &req); err != nil {
71 // We can't unmarshal the message body. That could be due to a bug or
72 // change in the frontend, or maybe some other program is sending
73 // malformed messages.
74
75 // Ack the message, because if we can't unmarshal it then no one else can either.
76 msg.Ack()
77 // Don't terminate processing; maybe this is just one bad message.
78 log.Printf("unmarshaling request: %v", err)
79 return nil
80 }
81 log.Printf("received %+v", req)
82 order, err := createOrFindOrder(ctx, p.coll, &req)
83 if err != nil {
84 // There was a problem with the database, perhaps due to the network.
85 // Nack the message; perhaps another processor can succeed.
86 if msg.Nackable() {
87 msg.Nack()
88 }
89 // Assume the database error is permanent: terminate processing.
90 return err
91 }
92 if order == nil {
93 log.Printf("duplicate finished order %v", req.ID)
94 // We've already processed this order, so ack the message.
95 msg.Ack()
96 return nil
97 }
98 // At this point, order is an unfinished order in the database.
99 // Process it.
100 err = p.processOrder(ctx, order)
101 // Any processing errors are saved as notes in the order.
102 if err != nil {
103 order.Note = fmt.Sprintf("processing failed: %v", err)
104 order.OutImage = ""
105 }
106 // Save the finished order to the database.
107 err = p.coll.Update(ctx, order, docstore.Mods{
108 "OutImage": order.OutImage,
109 "Note": order.Note,
110 "FinishTime": time.Now(),
111 })
112 if err != nil {
113 // We couldn't save the order to the database.
114 // Nack the message; perhaps another processor can succeed.
115 if msg.Nackable() {
116 msg.Nack()
117 }
118 // Assume the database error is permanent: terminate processing.
119 return err
120 }
121 // We've successfully processed the image.
122 msg.Ack()
123 return nil
124 }
125
126 // createOrFindOrder either creates a new order from req (the usual case), or returns an
127 // existing unfinished order. It returns a nil *Order if the order exists and is
128 // finished, that is, this request message is a duplicate.
129 // createOrFindOrder returns a non-nil error only for database problems.
130 func createOrFindOrder(ctx context.Context, coll *docstore.Collection, req *OrderRequest) (*Order, error) {
131 // See if there is already a document for this order.
132 order := &Order{ID: req.ID}
133 err := coll.Get(ctx, order)
134 if err != nil {
135 if gcerrors.Code(err) != gcerrors.NotFound {
136 return nil, err
137 }
138 // Normal case: the order wasn't found, because it hasn't been created
139 // yet. Create it.
140 order = &Order{
141 ID: req.ID,
142 Email: req.Email,
143 InImage: req.InImage,
144 CreateTime: req.CreateTime,
145 }
146 if err := coll.Create(ctx, order); err != nil {
147 return nil, err
148 }
149 return order, nil
150 }
151 if order.FinishTime.IsZero() {
152 // The order exists, but was not finished. Either it was abandoned by the processor that
153 // was working on it (probably because the processor died), or it is in progress. Assume
154 // that it was abandoned, and process it.
155 return order, nil
156 }
157 // The order exists and was finished. This is most likely the result of a pubsub redelivery.
158 // We simply ignore it.
159 return nil, nil
160 }
161
162 // processOrder processes the order request.
163 func (p *processor) processOrder(ctx context.Context, order *Order) error {
164 // Read the input image from the bucket.
165 r, err := p.bucket.NewReader(ctx, order.InImage, nil)
166 if err != nil {
167 return err
168 }
169
170 defer r.Close()
171 img, format, err := image.Decode(r)
172 if err != nil {
173 return err
174 }
175
176 // Process and write the output image.
177 order.OutImage = fmt.Sprintf("%s-out.png", strings.TrimSuffix(order.InImage, "-in"))
178 w, err := p.bucket.NewWriter(ctx, order.OutImage, nil)
179 if err != nil {
180 return err
181 }
182 if err := png.Encode(w, img); err != nil {
183 w.Close()
184 return err
185 }
186 if err := w.Close(); err != nil {
187 return err
188 }
189
190 // Pretend that the conversion takes some time.
191 time.Sleep(time.Duration(rand.Intn(5)+2) * time.Second)
192
193 order.Note = fmt.Sprintf("converted from %s to png", format)
194 return nil
195 }