Question

Using CopyObjectCommand in spaces with s3. "NoSuchBucket"

Hi everyone,

Hoping someone can help me out. I’m using DigitalOcean spaces and I want to back-up spaces to another space in another region.

I’m using the Node.js library “@aws-sdk/client-s3”. When I use the “CopyObjectCommand” to copy files between spaces in the same region it works perfectly fine. However, when I try to do it across regions it no longer works.

My flow: I instantiate a client in the “Origin” region, like this:

GetOriginClient(Space){
  return new S3Client({
    region: Space.region,
    endpoint: "https://"+Space.region+".digitaloceanspaces.com",
    credentials:{
      accessKeyId:process.env.DO_SPACES_ACCESS_KEY,
      secretAccessKey:process.env.DO_SPACES_ACCESS_SECRET
    }
  });
}

I then use “ListObjectsCommand” to get all the keys in the Origin space, which also works fine. Next I instantiate a DestinationClient in the same way, except in a different region. Finally, I instantiate a CopyObject command for each of the Objects i received, with the following params:

{
  Bucket: 'destination-bucket'
  CopySource: 'origin-bucket/backup/folder/subfolder/file.txt',
  Key: 'folder/subfolder/file.txt'
}

I also tried adding the source region (but i read this is not nescecery):

{
  Bucket: 'destination-bucket',
  CopySource: 'ams3/origin-bucket/backup/folder/subfolder/file.txt',
  Key: 'folder/subfolder/file.txt'
}

Getting error code 404, Code: ‘NoSuchBucket’. Any ideas?


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

alexdo
Site Moderator
Site Moderator badge
December 15, 2023

Heya,

On top of what’s already been mentioned I would like to add that spaces can also be backed-up using snapshooter.

Spaces are very reliable, but it’s always a good idea to back things up. Snapshooter (https://snapshooter.com/) and Flexify (https://flexify.io/) both have the ability to replicate data to another bucket in another region on a scheduled basis. You can also run free a tool like rclone (https://rclone.org/) paired with a cron job to copy files to another bucket in another region on a regular schedule.

Regards

Bobby Iliev
Site Moderator
Site Moderator badge
December 15, 2023

Hey!

Indeed, the CopyObjectCommand is not supported by the Spaces API. You can find a complete list of the Spaces API Reference Documentation here:

https://docs.digitalocean.com/reference/api/spaces-api/

I’ve just tested your code and indeed I’m getting the same error as you mentioned.

The best thing to do to get your voice heard regarding this would be to head over to our Product Ideas board and post a new idea, including as much information as possible for what you’d like to see implemented.

https://ideas.digitalocean.com/

Feel free to share the link to the idea here so other people and me could upvote it!

In the meantime, a workaround would be to manually handle the copying process. This involves two main steps:

  1. Download the Object from the Origin Space: Use the SDK to download the object from the origin space to your local server or a temporary storage location.

  2. Upload the Object to the Destination Space: Once the object is downloaded, use the SDK again to upload it to the destination space.

Here is an example code that I’ve tested and can confirm that is working:

const { S3Client, GetObjectCommand, PutObjectCommand } = require("@aws-sdk/client-s3");
const fs = require('fs');
const path = require('path');

// Initialize the S3 Client for the origin space
function getOriginClient(space) {
  return new S3Client({
    region: 'us-east-1',  // Default region for SDK compatibility
    endpoint: `https://${space.region}.digitaloceanspaces.com`,
    credentials: {
      accessKeyId: process.env.DO_SPACES_ACCESS_KEY,
      secretAccessKey: process.env.DO_SPACES_ACCESS_SECRET
    }
  });
}

// Initialize the S3 Client for the destination space
function getDestinationClient(space) {
  return new S3Client({
    region: 'us-east-1',  // Default region for SDK compatibility
    endpoint: `https://${space.region}.digitaloceanspaces.com`,
    credentials: {
      accessKeyId: process.env.DO_SPACES_ACCESS_KEY,
      secretAccessKey: process.env.DO_SPACES_ACCESS_SECRET
    }
  });
}

// Function to download an object from the origin space
async function downloadObject(client, bucket, objectKey, downloadPath) {
  const command = new GetObjectCommand({
    Bucket: bucket,
    Key: objectKey
  });

  try {
    const data = await client.send(command);
    const fileStream = fs.createWriteStream(downloadPath);
    data.Body.pipe(fileStream);
    return new Promise((resolve, reject) => {
      fileStream.on('close', resolve);
      fileStream.on('error', reject);
    });
  } catch (error) {
    console.error("Error downloading object:", error);
  }
}

// Function to upload an object to the destination space
async function uploadObject(client, bucket, objectKey, uploadPath) {
  const fileStream = fs.createReadStream(uploadPath);

  const command = new PutObjectCommand({
    Bucket: bucket,
    Key: objectKey,
    Body: fileStream
  });

  try {
    const response = await client.send(command);
    console.log("Object uploaded successfully:", response);
  } catch (error) {
    console.error("Error uploading object:", error);
  }
}

// Download and then upload the object
async function manualCopyObject(originSpace, destinationSpace, objectKey) {
  const originClient = getOriginClient(originSpace);
  const destinationClient = getDestinationClient(destinationSpace);

  const tempDownloadPath = path.join(__dirname, objectKey); // Temporary local path for download

  await downloadObject(originClient, originSpace.name, objectKey, tempDownloadPath);
  await uploadObject(destinationClient, destinationSpace.name, objectKey, tempDownloadPath);

  // Optionally, delete the local temporary file after upload
  fs.unlinkSync(tempDownloadPath);
}

// Example usage
const originSpace = { name: 'origin-spaces-name', region: 'nyc3' };  // Replace with your origin space details
const destinationSpace = { name: 'destination-spaces-name', region: 'fra1' };  // Replace with your destination space details
const objectKey = 'somefile.txt';  // Replace with your object key

// Example usage
manualCopyObject(originSpace, destinationSpace, objectKey);

Hope that helps!

- Bobby.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.