forked from awslabs/aws-java-nio-spi-for-s3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathS3SeekableByteChannel.java
306 lines (271 loc) · 10.6 KB
/
S3SeekableByteChannel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.nio.spi.s3;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.nio.spi.s3.util.TimeOutUtils;
class S3SeekableByteChannel implements SeekableByteChannel {
private static final Logger LOGGER = LoggerFactory.getLogger(S3SeekableByteChannel.class);
private final Set<? extends OpenOption> options;
private long position;
private final S3Path path;
private final ReadableByteChannel readDelegate;
private final S3WritableByteChannel writeDelegate;
private boolean closed;
private long size = -1L;
S3SeekableByteChannel(S3Path s3Path, S3AsyncClient s3Client, Set<? extends OpenOption> options) throws IOException {
this(s3Path, s3Client, 0L, options, null, null);
}
private S3SeekableByteChannel(S3Path s3Path, S3AsyncClient s3Client, long startAt, Set<? extends OpenOption> options,
Long timeout, TimeUnit timeUnit) throws IOException {
position = startAt;
path = s3Path;
closed = false;
this.options = options;
s3Path.getFileSystem().registerOpenChannel(this);
if (options.contains(StandardOpenOption.SYNC) || options.contains(StandardOpenOption.DSYNC)) {
throw new IOException("The SYNC/DSYNC options is not supported");
}
var config = s3Path.getFileSystem().getConfiguration();
if (options.contains(StandardOpenOption.WRITE)) {
LOGGER.debug("using S3WritableByteChannel as write delegate for path '{}'", s3Path.toUri());
readDelegate = null;
var transferUtil = new S3TransferUtil(s3Client, timeout, timeUnit);
writeDelegate = new S3WritableByteChannel(s3Path, s3Client, transferUtil, options);
position = 0L;
} else if (options.contains(StandardOpenOption.READ) || options.isEmpty()) {
LOGGER.debug("using S3ReadAheadByteChannel as read delegate for path '{}'", s3Path.toUri());
readDelegate =
new S3ReadAheadByteChannel(s3Path, config.getMaxFragmentSize(), config.getMaxFragmentNumber(), s3Client, this,
timeout, timeUnit);
writeDelegate = null;
} else {
throw new IOException("Invalid channel mode");
}
}
/**
* Reads a sequence of bytes from this channel into the given buffer.
*
* <p> Bytes are read starting at this channel's current position, and
* then the position is updated with the number of bytes actually read.
* Otherwise, this method behaves exactly as specified in the {@link
* ReadableByteChannel} interface.
*
* @param dst the destination buffer
* @return the number of bytes read or -1 if no more bytes can be read.
*/
@Override
public int read(ByteBuffer dst) throws IOException {
validateOpen();
if (options.contains(StandardOpenOption.WRITE) && options.contains(StandardOpenOption.READ)) {
return writeDelegate.read(dst);
}
if (readDelegate == null) {
throw new NonReadableChannelException();
}
return readDelegate.read(dst);
}
/**
* Writes a sequence of bytes to this channel from the given buffer.
*
* <p> Bytes are written starting at this channel's current position, unless
* the channel is connected to an entity such as a file that is opened with
* the {@link StandardOpenOption#APPEND APPEND} option, in
* which case the position is first advanced to the end. The entity to which
* the channel is connected will grow to accommodate the
* written bytes, and the position updates with the number of bytes
* actually written. Otherwise, this method behaves exactly as specified by
* the {@link WritableByteChannel} interface.
*
* @param src the src of the bytes to write to this channel
*/
@Override
public int write(ByteBuffer src) throws IOException {
validateOpen();
if (writeDelegate == null) {
throw new NonWritableChannelException();
}
return writeDelegate.write(src);
}
/**
* Returns this channel's position.
*
* @return This channel's position,
* a non-negative integer counting the number of bytes
* from the beginning of the entity to the current position
*/
@Override
public long position() throws IOException {
validateOpen();
if (writeDelegate != null) {
return writeDelegate.position();
}
synchronized (this) {
return position;
}
}
/**
* Sets this channel's position.
*
* <p> Setting the position to a value that is greater than the current size
* is legal but does not change the size of the entity. A later attempt to
* read bytes at such a position will immediately return an end-of-file
* indication. A later attempt to write bytes at such a position will cause
* the entity to grow to accommodate the new bytes; the values of any bytes
* between the previous end-of-file and the newly-written bytes are
* unspecified.
*
* <p> Setting the channel's position is not recommended when connected to
* an entity, typically a file, that is opened with the {@link
* StandardOpenOption#APPEND APPEND} option. When opened for
* append, the position is first advanced to the end before writing.
*
* @param newPosition The new position, a non-negative integer counting
* the number of bytes from the beginning of the entity
* @return This channel
* @throws ClosedChannelException If this channel is closed
* @throws IllegalArgumentException If the new position is negative
* @throws IOException If some other I/O error occurs
*/
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
if (newPosition < 0) {
throw new IllegalArgumentException("newPosition cannot be < 0");
}
if (!isOpen()) {
throw new ClosedChannelException();
}
if (writeDelegate != null) {
writeDelegate.position(newPosition);
return this;
}
// this is only valid to read-only channels
if (readDelegate == null) {
throw new NonReadableChannelException();
}
synchronized (this) {
position = newPosition;
return this;
}
}
/**
* Returns the current size of entity to which this channel is connected.
*
* @return The current size, measured in bytes
* @throws IOException If some other I/O error occurs
*/
@Override
public long size() throws IOException {
validateOpen();
if (writeDelegate != null) {
return writeDelegate.size();
}
if (size < 0) {
fetchSize();
}
return this.size;
}
private void fetchSize() throws IOException {
synchronized (this) {
this.size = S3BasicFileAttributes.get(path, Duration.ofMinutes(TimeOutUtils.TIMEOUT_TIME_LENGTH_1)).size();
LOGGER.debug("size of '{}' is '{}'", path.toUri(), this.size);
}
}
/**
* Truncates the entity, to which this channel is connected, to the given
* size.
*
* <p> If the given size is less than the current size then the entity is
* truncated, discarding any bytes beyond the new end. If the given size is
* greater than or equal to the current size then the entity is not modified.
* In either case, if the current position is greater than the given size
* then it is set to that size.
*
* <p> An implementation of this interface may prohibit truncation when
* connected to an entity, typically a file, opened with the {@link
* StandardOpenOption#APPEND APPEND} option.
*
* @param size The new size, a non-negative byte count
* @return This channel
*/
@Override
public SeekableByteChannel truncate(long size) {
throw new UnsupportedOperationException("Currently not supported");
}
/**
* Tells whether this channel is open.
*
* @return {@code true} if, and only if, this channels delegate is open
*/
@Override
public boolean isOpen() {
synchronized (this) {
return !this.closed;
}
}
/**
* Closes this channel.
*
* <p> After a channel is closed, any further attempt to invoke I/O
* operations upon it will cause a {@link ClosedChannelException} to be
* thrown.
*
* <p> If this channel is already closed then invoking this method has no
* effect.
*
* <p> This method may be invoked at any time. If some other thread has
* already invoked it, however, then another invocation will block until
* the first invocation is complete, after which it will return without
* effect. </p>
*/
@Override
public void close() throws IOException {
synchronized (this) {
if (readDelegate != null) {
readDelegate.close();
}
if (writeDelegate != null) {
writeDelegate.close();
}
closed = true;
path.getFileSystem().deregisterClosedChannel(this);
}
}
private void validateOpen() throws ClosedChannelException {
if (this.closed) {
throw new ClosedChannelException();
}
}
/**
* Access the underlying {@code ReadableByteChannel} used for reading
*
* @return the channel. May be null if opened for writing only
*/
ReadableByteChannel getReadDelegate() {
return this.readDelegate;
}
/**
* Access the underlying {@code WritableByteChannel} used for writing
*
* @return the channel. May be null if opened for reading only
*/
WritableByteChannel getWriteDelegate() {
return this.writeDelegate;
}
}